Quick question regarding memory management in C++
If I do the following operation:
pointer = new char [strlen(someinput_input)+1];
And then perform it again, with perhaps a different result being returned from strlen(someinput_input)
.
Does this result in memory being left allocated from the previous "new
" statement? As in, is each new
statement receiving another block of HEAP memory from the OS, or is it simply reallocating?
Assuming I do a final delete pointer[];
will that deallocate any and all memory that I ever allocated via new
to that pointer?
New and Delete Operator In C++ when we want to allocate memory from the free-store (or we may call it heap) we use the new operator. int *ptr = new int; and to deallocate we use the delete operator.
No! When realloc() has to copy the allocation, it uses a bitwise copy operation, which will tear many C++ objects to shreds. C++ objects should be allowed to copy themselves.
In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes.
Local variables are allocated automatically when a function is called, and they are deallocated automatically when the function exits. Heap memory is different in every way. The programmer explicitly requests that space be allocated, using the new operator in Java or C++.
Does this result in memory being left allocated from the previous "new" statement?
Yes, this is called a memory leak.
IE, is each new statement receiving another block of HEAP memory from the OS, or is it simply reallocating?
It is a new block of memory from the heap.
Assuming I do a final delete pointer[]; will that deallocate any and all memory that I ever allocated via new to that pointer?
If you "delete [] pointer;", it will deallocate the memory that it points to. Only the memory from the last "new char[]" call.
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