Strcpy Segmentation Fault C

user3623498 picture user3623498 · Aug 27, 2014 · Viewed 9.5k times · Source

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;
}

Answer

PaulMcKenzie picture PaulMcKenzie · Aug 27, 2014

The problems start here:

name=(char *)malloc(60*sizeof(char));
name="Hello World!";

You replaced the value returned by malloc with a string literal.

  1. 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.

  2. You further on write to a NULL pointer, which is undefined behavior (which in your case, produced a segmentation fault).