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
#include
#include
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;
}
Solved
You need to allocate memory for altname :
#include
#include
#include
int main()
{
char *name;
char *altname;
name=(char *)malloc(60*sizeof(char));
name="Hello World!";
altname=name;
printf("%s \n", altname);
altname=NULL;
// allocate memory, so strcpy has space to write on ;)
altname=(char *)malloc(60*sizeof(char));
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 tomallocare matched with a corresponding call tofree. Since that pointer value is gone, the opportunity to callfreewith 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).
The first time, you are making altname point to the same place as name. This is OK, because name points to a valid char* (the first element ofthe "Hello World!" literal)
// both point to beginning of "Hello World!" literal
altname=name;
The second time, you attempt to copy the data pointed at by name into the place pointed at by altname, which at this stage points to NULL. So you attempt to write to NULL, which is the source of the error.
strncpy requires that the destination buffer be writable, and large enough to copy the source string's data into. You need to make altname point to a buffer that is large enough for the contents of the string name points to.
altname = (char*)malloc(60*strlen(name)+1); // +1 for nul terminator
strcpy(altname, name);
Also note that when you set name = "Hello World!", you leak the memory it originally pointed to. You need to free that first:
free(name);
name = "Hello World!";
You are trying to assign value to altname which has no space to store. First allocate memory to altname then assign
#include
#include
#include
int main()
{
char *name;
char *altname;
name=(char *)malloc(60*sizeof(char));
name="Hello World!";
altname=name;
printf("%s \n", altname);
altname=NULL;
altname=(char *)malloc(sizeof(name)); // allocate memory
strcpy(altname,name); // Now assign
printf("%s \n", altname);
return 1;
}
Comments
Post a Comment