I am learning some new things and get stuck on a simple strcpy operation. I don't understand why first time when I print works but second time it doesn't.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *name;
char *altname;
name=(char *)malloc(60*sizeof(char));
name="Hello World!";
altname=name;
printf("%s \n", altname);
altname=NULL;
strcpy(altname,name);
printf("%s \n", altname);
return 1;
}
The problems start here:
name=(char *)malloc(60*sizeof(char));
name="Hello World!";
You replaced the value returned by malloc
with a string literal.
You leaked memory (since you can't regain the pointer value returned by malloc
). All calls to malloc
are matched with a corresponding call to free
. Since that pointer value is gone, the opportunity to call free
with that pointer value is also gone.
You further on write to a NULL pointer, which is undefined behavior (which in your case, produced a segmentation fault).