Deadlock
Deadlock

Reputation: 4519

Memory usage with pointers

Please look at the below image. After changing the value of p1, now it points to the B2 memory location. What happened to the shaded memory segment? As i know It will remain until code block finished its execution. Can those garbaged memory segments be reused again for program execution?

char *p1 = "String";
char *p2 = "Another";
p1 = p2;

Question title may be misleading. I was unable to find a qood title for this question. enter image description here

Upvotes: 8

Views: 159

Answers (3)

pri
pri

Reputation: 1531

It will keep dangling in the memory as long as it is not cleared by the system. "Dangling" because there is no pointer which is pointing to that string.

Upvotes: 0

anon
anon

Reputation:

There's no need that this specific memory segment be used again during the program's execution. These parts remain in memory until the program's life comes to an end. Even if, at some point, you re-write the command:

p1 = "String";

it doesn't mean that p1 will point to that specific memory segment. It may, but it may not.

Upvotes: 0

Shoe
Shoe

Reputation: 76298

What happened to the shaded memory segment? As i know It will remain until code block finished its execution.

As per §2.13.5/8 a string literal has static storage duration:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

which means that, as per §3.7.1/1, they last for the duration of the program:

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).

As a side note, you should really assign string literals to char const* or char const[], not to char*. The reason why it mostly work in compilers is for backward compatibility reasons and in C++11 it has been deprecated.


Can those garbaged memory segments be reused again for program execution?

According to §2.13.5/16 it's unspecified whether they are reused or not:

Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified. [ Note: The effect of attempting to modify a string literal is undefined. — end note ]

Upvotes: 6

Related Questions