I wrote the sample program below to demsonstrate a problem I am having. Basically, I have written a method that will create a copy of a struct that was created in main(). My goal is to free the memory that was used by both the original struct and the copy by the program's end. However, it crashes after returning from the copy method when I attempt to free the original structure. It is my understanding that if I do not free both I will have a memory leak situation. Does anyone know why the free()'s in main() crash this program?
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define STRINGA "abcdefghijklm"
#define STRINGB "nopqrstuvwxyz"
struct stuff
{
char* a;
char* b;
};
int main()
{
struct stuff *original = malloc(sizeof(struct stuff));
original->a = malloc(strlen(STRINGA));
strcpy(original->a, STRINGA);
original->b = malloc(strlen(STRINGB));
strcpy(original->b, STRINGB);
printf("original->a: %s\n", original->a);
printf("original->b: %s\n", original->b);
copy((void*)original);
free(original->a);
free(original->b);
free(original);
}
void copy(void *ptr)
{
printf("ptr->a: %s\n", ((struct stuff *)ptr)->a);
printf("ptr->b: %s\n", ((struct stuff *)ptr)->b);
struct stuff *new = malloc(sizeof(struct stuff));
memcpy(new, ptr, sizeof(struct stuff));
printf("new->a: %s\n", new->a);
printf("new->b: %s\n", new->b);
free(((struct stuff *)ptr)->a);
free(((struct stuff *)ptr)->b);
free((struct stuff *)ptr);
}