Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free an array in C/C++ [closed]

int main() {
    // Will this code cause memory leak?
    // Do I need to call the free operator?
    // Do I need to call delete?
    int arr[3] = {2, 2, 3};
    return 0;
}
  1. Does this code create a memory leak?

  2. Where does arr reside? On the stack or in RAM?

like image 597
Dr. Programmer Avatar asked Oct 25 '15 22:10

Dr. Programmer


People also ask

How do I free an array in C?

You should do: for (int i=0; i<10; i++) { free(array[i]); } free(array); Ad. Example 1: array is allocated on the stack ("automatic variable") and cannot be released by free . Its stack space will be released when the function returns.

Do you have to free an array in C?

no, you must not free such an array. There's a reason non-static local variables are said to have automatic storage duration… Also, forget about "the stack" and "the heap". The C standard only specifies abstract semantics for automatic, static and dynamic storage duration.

How do I delete an array for free?

You can just use free to delete a dynamically allocated array. int* array = malloc(10*sizeof(int)); ... free(array); If you allocated memory for each array element, you'll also need to free each element first. Save this answer.

Can you remove from an array in C?

In C programming, an array is derived data that stores primitive data type values like int, char, float, etc. To delete a specific element from an array, a user must define the position from which the array's element should be removed. The deletion of the element does not affect the size of an array.


1 Answers

In this program

int main() {
    // Will this code cause memory leak?
    // Do I need to call the free operator?
    // Do I need to call delete?
    int arr[3] = {2, 2, 3};
    return 0;
}

array arr is a local variable of function main with the automatic storage duration. It will be destroyed after the function finishes its work.

The function itself allocated the array when it was called and it will be destroyed afetr exiting the function.

There is no memory leak.

You shall not call neither C function free nor the operator delete [].

If the program would look the following way

int main() {
    int *arr = new int[3] {2, 2, 3};
    //...
    delete [] arr;
    return 0;
}

then you should write operator delete [] as it is shown in the function.

like image 73
Vlad from Moscow Avatar answered Sep 25 '22 07:09

Vlad from Moscow