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