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?

4
  • 4
    Yep, that's a memory leak. Commented Jun 1, 2017 at 8:10
  • That's correct (given by "allocate memory" you really mean a call to malloc()), so do you have any other questions? Commented Jun 1, 2017 at 8:10
  • btw, if char *p is already defined, your line is a syntax error. Commented Jun 1, 2017 at 8:10
  • Take a look here : stackoverflow.com/questions/4970823/… Commented Jun 1, 2017 at 8:13

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 you should ask another question
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.

Comments

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"; 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.