FLOWMEEN
FLOWMEEN

Reputation: 395

How to free memory on stack mid-function call

Say I have an array arr[10], and then I copy all elements to another array, arr2[20]. I no longer need arr, so I do arr=arr2 to move its pointer to the new array. Is the memory that was used by arr[10] still used, or is it freed automatically? If it's still used, is there a way for me to free it before reassigning the pointer?

Upvotes: 0

Views: 51

Answers (2)

SegFault
SegFault

Reputation: 2546

If you declared arr like int arr[10]; then it will be stored on the stack, and will be freed when the function ends. You generally can't free stack memory mid function.

If you defined it using malloc() then it will be on the heap and you have to use free() to free it. Or else it will be a memory leak and be freed after your program exits. However, even if you get a memory leak, you computer will always be able to retrieve that memory because of virtual memory.

Upvotes: 1

tdao
tdao

Reputation: 17668

Is the memory that was used by arr[10] still used, or is it freed automatically?

It depends on how you actually declare your array.

  • If you declare it as an automatic variable, then it's freed automatically when the function call ends.
  • If you do some dynamic allocation, then it will exist after the function call ends, and you would have to free it manually.

Upvotes: 0

Related Questions