dynamic memory

Apr 29, 2010 at 5:31pm
When you free the memory of dynamic memory, like:
1
2
char* text[] = "Hello World!";
delete[] text;

it frees the memory that text used of course. But how will a system know how much to free or how big the used space is? I think that the system will need to reserve extra space in memory to save how big the dynamic memory array is. Or am I wrong? If so, why does C++ not have any way to retrieve the size?

Thanks in advance!
Apr 29, 2010 at 5:40pm
Your above code is nonsense, but to answer your question:

When malloc returns a pointer P to you, the memory manager (malloc) stores some
information about the size of the block just allocated in the bytes immediately prior
to P in memory. When you free( P ), free looks at those bytes to figure out the
length of the block.

Note: new uses malloc in all implementations I'm aware of and therefore works similarly.

Apr 29, 2010 at 6:28pm
If so, why does C++ not have any way to retrieve the size?
Because where, how, and even whether the size is stored is implementation-defined. For example, this might work on a hypothetical compiler:
1
2
char *buffer=malloc(n);
size_t size=*(size_t *)(buffer-4);
But it's very unlikely to work on a different compiler.
May 1, 2010 at 9:21am
ok thanks. Btw, I actually meant this line:
char* text[] = "Hello World!";
to be this line:
char* text = "Hello World!";

Anyway, thanks for answering my question. Too bad that dynamic memory doesn't have any standard way to retrieve the size :P.
May 1, 2010 at 9:58am
I'd like to point out that even then that code is incorrect. Deleting a pointer to a read-only array such as a string literal will practically always crash the program.
May 1, 2010 at 10:57am
What jsmith and helios want to say about your example is that the memory reserved for text is not dynamically allocated, so not only there is no need to use delete[]/delete on it but doing so can actually cause problems. Only use delete/delete[]/free on memory you reserve with new/new[]/malloc respectively.
Last edited on May 1, 2010 at 11:00am
Topic archived. No new replies allowed.