c++ - How do you know how to deallocate an array of pointers? -


if have array of pointers this:

char* p[3];  p[0] = new char; p[1] = new char[10]; p[2] = &c; 

assuming cannot use std::string, how know how deallocate without seeing definition? how know use delete or delete[] while iterating through array, or whether points stack variable or on heap?

short answer: don't, unless know how allocated way code written.

long answer: there no (generic, portable way) determine how or if allocated individual element new char or array new char[10]; or not allocated @ all. in theory, check if address "within heap" if know heap is, there no simple way know heap, stack , global data without intimate knowledge of memory layout of particular system, , compile same code on different os or different processor architecture of same os, , changes. find out if it's single or array allocation harder, if @ possible [most c++ runtime not detect , complain when char *p = new char[10]; delete p; - crash/misbehave or "work anyway, because didn't matter", depending on luck, c++ runtime library design , machine architecture] - see further discussion below.

so have track part of code [or not write code @ all, preference], or use other construct (smart pointers work, vectors work).

further: if have method finding out whether came heap or not, still can't determine if it's "the original allocation or else". imagine following:

char *p[2];  p[0] = new char[10]; p[1] = p[0] + 3; 

now, p[1] points inside heap, not @ it's own allocation, @ location within allocation made p[0]. so, basically, it's near impossible this, if know heap, data , stack memory located - can't know generically.

as side note, people "the heap" if it's single contiguous piece of memory. isn't in modern os's, because there many different ways particular piece of memory may occupied. can allocated part of code, data or stack loaded initial loading of executable file. can part of shared library (.so or .dll, etc) [which has code , data space] - , given specific address avoid having 'relocate' shared library every user, , piece of memory memory mapped file or shared memory allocation - which, @ least sometimes, can given specific address in memory, , have address "in middle of 'heap' memory region". when "the heap", mean "any free memory address os thinks can use storing things in", rather 1 straight line of addresses b no holes. it's more a-b, f-j, m, p , t-v "the heap".

and marcus mentions in comment, there os's intentionally "move things around" (address space randomization) make harder illicit purposes rely on distance 1 memory region abuse stack overwriting "crack" system.


Popular posts from this blog