chrishuang24
chrishuang24

Reputation: 1

where is the memory leak in the code below?

Can you guys help me to identify where is the memory leak?

void foo(char *name){
    char * p = (char *)malloc(1024);
    char * buf = (char *)malloc(1024);
    sprintf(p, "User name: %s", name);
    printf("Format string is %s\n", p); 
    buf = p;
    free(p);
    free(buf);
}

Upvotes: 0

Views: 68

Answers (2)

user3629249
user3629249

Reputation: 16540

this is the memory leak:

buf = p;

because it overlays one of the pointers to allocated memory.

However, due to the above statement, this statement:

free(buf);

will cause a program crash because the memory pointed to be buf has already been passed to free()

so, two bad things in the posted code.

To fix it all, remove this statement:

buf = p;

Upvotes: 0

ikegami
ikegami

Reputation: 385847

  1. You allocate a memory block we'll call BLOCK1. p initially points to BLOCK1.
  2. You allocate a memory block we'll call BLOCK2. buf initially points to BLOCK2.
  3. buf is changed to point to BLOCK1 (buf = p;). Nothing points to BLOCK2 now. Memory leak.
  4. You free BLOCK1 (free(p)), but you never free BLOCK2.

Also, you invoke undefined behaviour by attempting to free a block that has already been freed (free(buf)).

If you are trying to copy the string, strncpy or strcpy should be used in lieu of buf = p;.

If you are trying to copy the pointer, only allocate one block (using char *buf = p; in lieu of char *buf = malloc(...); buf = p;).

Upvotes: 3

Related Questions