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;
}
Does this code create a memory leak?
Where does arr
reside? On the stack or in RAM?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With