3

I'm trying out the following code:

int main()
{
   char *yo = "yo";
   char *whaddup = NULL;
   strcpy(whaddup,yo);
}

and I get a segfault. Complete C noob here - other places say I should initialize whaddup as an array. Why can't I pass in a pointer to null?

user2635088
  • 1,598
  • 1
  • 24
  • 43
  • Same reason you can't do `char *whaddup = NULL; *whaddup = 'a';` for example. Which is also the same reason you can't do `int *whaddup = NULL; *whaddup = 4;` – user253751 Jun 28 '16 at 02:07
  • @immibis whats the reason please? – user2635088 Jun 28 '16 at 02:53
  • A NULL pointer doesn't point to anything – user253751 Jun 28 '16 at 05:12
  • @immibis but we can do `char *in = NULL; in = fgets(you.first_name, 100, stdin);` where `you` is some struct. Does this mean we can assign a pointer to the variable `in` to make it point somewhere else, but not a literal? – user2635088 Sep 24 '16 at 12:47
  • Well `in` doesn't contain NULL after you assign something that isn't NULL to it. If I do `int in = 5; in = 4;` then in contains 4 after this runs, and doesn't contain 5. `in = something;` is not the same as `*in = something;` - the latter doesn't modify `in` – user253751 Sep 24 '16 at 21:18

3 Answers3

3

Just any strcpy documentation will tell you that the destination string should be a char array large enough to hold the string and the NUL terminator.

So what you need is something like

char* yo = "yo";
char* whaddup = malloc(strlen(yo)+1);
strcpy(whaddup, yo);

Or alternatively you could use strdup function which does this for you, but it's not standard as it's POSIX only.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • I only included the sizeof(char) to demonstrate the conceptual memory allocation, but yes @user2635088 a character is one byte so you don't need it. Safe to get in the habit of using it when you begin allocating int, double, etc. – Jack Ryan Jun 28 '16 at 01:49
1

You have to either declare whaddup as a character array or ideally allocate space for it with malloc.

int main()
{
   char *yo = "yo";
   char *whaddup = malloc(sizeof(char) * 8); // buffer for 8 characters
   strcpy(whaddup,yo);
}

By initializing whaddup to NULL you are not giving it any space in memory, so even copying one character into it will result in a segmentation fault.

Jack Ryan
  • 1,287
  • 12
  • 26
0

You can pass in a pointer to null, but you can not copy string from pointer to null.

The function char* strcpy(char* dest, const char* src) is copy string from address src to address dest, your dest is null.