0

When you allocate memory to char* p, it has memory location at heap section it points to. However, once the following line is executed, would it point to new memory location at Data section and assign pointer to it?

char* p = "newstring";

If so, there is no way to find the allocated memory and free it afterward?

user694733
  • 15,208
  • 2
  • 42
  • 68

4 Answers4

3

Having e.g.

char *p;
p = malloc(SOME_SIZE);
p = "some string";

is equivalent to

int i;
i = 5;
i = 10;

When you reassign a pointer to point somewhere else, you loose the original value of the pointer, where it originally pointed. That will lead to a memory leak.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • thanks! one quick question. beside my question with memory leak. regarding the segment of the memory wise, if int i has allocated memory, the int i will be pointing the same section of memory at heap, right? However, since char* is pointer, even after memory is allocated it points to new memory location. Is my understanding correct? – Dev_new Jun 01 '17 at 08:33
  • @Dev_new you should ask another question – Jabberwocky Jun 01 '17 at 08:42
2

The simple answer is no. Once you have overwritten your copy of the pointer, then you can't get it back again.

In reality, the memory manager has knowledge of the pointer, but there is no standard way to get it.

Neil
  • 11,059
  • 3
  • 31
  • 56
0

Keep copy of p pointer value to free it:

char * pp = p;
p = "newstring";
...
free( pp );

Or free before new assignment:

free( p ); // only if p is previously assigned with malloc()
p = "newstring";
i486
  • 6,491
  • 4
  • 24
  • 41
0

No cause the old value of the pointer is lost forever (unless you cache it somewhere). This lead to a memory leak, memory that is allocated but not referenced by any alive pointer.

int main() {
    ios_base::sync_with_stdio(false);

    char* p = (char*)malloc(sizeof(char)*100);
    printf("%p\n",p);

    p = "random string";
    printf("%p\n",p);
    return 0;
}

outputs something like: 0x55592ed2cc80 0x55592da03f24

If you need to free the pointer then cache the value you are about to overwrite.

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36