CBegin said:
Marc said:
ptr is a pointer that point on the automatic read-only
char array "TestString".
Thanks a lot,
Is this whats happening internally:
char *ptr = "TestString";
gets expanded to:
const char temp[] = "TestString";
ptr = temp; // ptr holds the address of read only buffer
//
so when i try free p, it actually tries to clean the memory assigned to
temp variable,
Almost. String literals have static duration (i.e., they do not get
deallocated when you leave the block where you "define" them (scare
quotes around "define" because it's clearly not a real definition as,
ahem, defined in the C Standard, but the thing comes into existence
nevertheless and you asked for it to exist)); and string literals are
not modifiable, but (for reasons of convenience) not acutally const; so
the definition of temp should actually be
static char temp[] = "TestString";
but you still can't write to it.
Apart from that, yes, that's more or less what happens behind the
scenes.
which is not stored in heap, but on stack.
No. First, there is no guarantee that allocated objects are stored in a
structure called (or even necessarily describable as) "the heap"; and
there is no guarantee that the area in which automatic objects are
stored is called "the stack", although it _is_ very unlikely not to be
arranged as one.
Second, as I wrote above, string literals have static duration. This is
a third category, separate from objects with allocated duration ("the
heap") and objects with automatic duration ("the stack"). It is often
called something like "global memory".
Basically, allocated memory (memory you get from malloc() and friends)
exists from the point at which you ask for it, until the point you
free() it (or, AFAIK, in C++, delete it). Automatic memory, which is all
normal objects defined within a function, exists from the start of the
block it is declared in until the end of that block. Static memory,
which is all objects declared outside a function as well as all objects
declared static, _and_ your string literal, exists as long as the
program runs.
(C99 adds some subtleties to this, involving things like compound
literals and variable length arrays, but you need not concern yourself
with these - yet.)
The effect on your program, though, is the same. You cannot free()
static memory any more than you can free() automatic memory. You can
only call free() on memory you have received from malloc(), calloc() or
realloc(), and even then only on the base pointer of the block, not on
any pointer inside it; and only once per memory block.
Richard