Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C free char* allocated on heap

Is there a memory leak in the following code example as I have allocated memory on the heap for name which hasn't been freed? If I add free(person->name); before the free(person); line then I get a runtime error in VS "CRT detected that the application wrote to memory after end of heap buffer".

header.h:

#ifndef HEADER
#define HEADER

typedef struct person {
 char *name;
} Person;

#endif

source.c:

#include <stdio.h>
#include <stdlib.h>
#include "header.h"

#define BUFFERSIZE 500

int main (int argc, char* argv[]){
 Person *person = NULL;
 char buffer[BUFFERSIZE];
 printf("Enter name\n");
 fgets(buffer, BUFFERSIZE, stdin);
 {
  char *name; 
  person = malloc(sizeof(Person));
  name = malloc(strlen(buffer));
  strcpy (name,buffer);
  person->name = name;
 }
 free(person); 
 return 0;
}

Thanks, Rob

like image 618
robdavies35 Avatar asked Oct 24 '10 19:10

robdavies35


3 Answers

strlen doesn't account for the null-terminator that strcpy adds, you'll need to "malloc(strlen(buffer)+1)"

like image 79
Adam Vandenberg Avatar answered Oct 17 '22 07:10

Adam Vandenberg


Yes, the code has a memory leak.

The culprit is: name = malloc(strlen(buffer)); which should be
name = malloc(strlen(buffer)+1); to account for \0.

You should now be able to free person->name.

like image 9
David Titarenco Avatar answered Oct 17 '22 05:10

David Titarenco


Yes. There is a memory leak.

You allocate a name buffer:

name = malloc(strlen(buffer));

and never deallocate it. Then when you deallocate the Person,

free(person); 

you lose your last pointer to that buffer, so you can never deallocate it.

The error message you are getting is a separate issue related to the length of the name buffer that you allocate being insufficient to include the null termination of the string you try to copy into it.

like image 3
dmckee --- ex-moderator kitten Avatar answered Oct 17 '22 05:10

dmckee --- ex-moderator kitten