Edshiwn
Edshiwn

Reputation: 19

what happen to memory assigned to a string addressed by a pointer when that pointer points to a new string?

    char *p = "hello";
    p = "hello_2";

Here string "hello" was stored in memory and its address was present in pointer 'p' but when this pointer starts pointing to string "hello_2", what will happen to the memory where the string "hello" was stored? Will it be freed or this string remains there but we can't access it?

Upvotes: 1

Views: 85

Answers (4)

Siva Elango R
Siva Elango R

Reputation: 19

There are different memory sections to which the globals, heap, code and string literals go to. It is specific to the compiler used.

gcc makes a .rodata section which is a read-only section and the string literals are stored there.

Visual C++ creates a .rdata section for the read only section.

You can use objdump (on linux) to check different sections for your binary.

Upvotes: 0

msc
msc

Reputation: 34588

You are actually creating a string literal named "hello" allocating it somewhere in the memory , and assigning the address of first character of the literal to the pointer p, and as the pointer is not constant you can assign it again with different addresses. And one more important point to note is that the string literal created are in read only memory.

Upvotes: 1

Gopi
Gopi

Reputation: 19864

What you have is a string constant and it is stored in read-only memory. So this memory is not required to be freed explicitly using free()

Till the lifetime of the variable p is valid you can access the stored string.

Upvotes: 2

mksteve
mksteve

Reputation: 13073

The memory will not be freed. But would not (in this case), be lost. The code knows where the string is, and uses it each time the fragment is run, to assign to the pointer p.

  • Memory which is on the heap does need to be freed (result of malloc or strdup).

  • Memory which is on the stack does not need to be freed.

  • Memory which is static (this case) does not need to be freed.

Upvotes: 1

Related Questions