David Villasmil
David Villasmil

Reputation: 415

Stack memory after pointer change

Say I do this:

const char *myvar = NULL;

Then later

*myval = “hello”;

And then again:

*myval = “world”;

I’d like to understand what happens to the memory where “hello” was stored?

I understand it is in the read only stack space, but does that memory space stays there forever while running and no other process can use that memory space?

Thanks

Upvotes: 0

Views: 30

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

String literals have static storage duration. They are usually placed by the compiler in a stack pool. So string literals are created before the program will run.

In these statements

*myval = “hello”;

*myval = “world”;

the pointer myval is reassigned by addresses of first characters of these two string literals.

Pat attention to that you may not change string literals. Whether the equal string literals are stored as a one character array or different character arrays with the static storage duration depends on compiler options.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

Assuming you meant

myval = "world";

instead, then

I’d like to understand what happens to the memory where “hello” was stored?

Nothing.

You just modify the pointer itself to point to some other string literal.

And string literals in C programs are static fixed (non-modifiable) arrays of characters, with a life-time of the full programs. The assignment really makes the pointer point to the first element of such an array.

Upvotes: 1

Related Questions