Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reallocating memory via "new" in C++

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?

like image 873
BSchlinker Avatar asked Apr 01 '10 02:04

BSchlinker


People also ask

How do you deallocate memory allocated by new?

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.

Can I use realloc with new?

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.

How can we dynamically allocate memory in C?

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.

Does New allocate memory on heap?

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++.


1 Answers

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.

like image 157
Stephen Avatar answered Oct 07 '22 20:10

Stephen