Antonio Pio Mennuni
Antonio Pio Mennuni

Reputation: 53

Problems in C with const char * and strcpy()

I don't understand why when I run strcpy (ss, ss2) with char * ss and char * ss2 it shows segmentation fault. strcpy () just asks for 2 args of type char *, so I don't understand the problem

#include <stdio.h>
#include <string.h>


int main()
{

  char *s;
  char *s2 = "hello";
  s = s2;
  printf ("s=%s\ns2=%s\n", s,s2);


  char *ss;
  char *ss2 = "hello";
  strcpy (ss, ss2);//why segmentation fault?
 
  printf("ss=%s\nss2=%s\n",ss,ss2);
}

return 0;

Upvotes: 0

Views: 805

Answers (2)

user123
user123

Reputation: 2884

When you write

char *s;
char *s2 = "hello";
s = s2;

You have s as a char pointer to 0. Then s2 as a char pointer to the h of hello. Then s takes the value of s2 that is the address of the h of hello.

While when you write

char *ss;
char *ss2 = "hello";
strcpy (ss, ss2);//why segmentation fault?

You have ss pointing to 0. You have ss2 pointing to the h of hello. Then you ask the strcpy function to put the hello string at address 0. This is wrong. You should allocate enough space for your string with

char ss[6];

Upvotes: -1

Alex
Alex

Reputation: 937

Your first block of statements works because you are assigning to s the location of the "hello" string.

In the second block of statements, ss has an undefined value and strcpy tries to write to that location, likely causing a segmentation fault.

To make it work you can declare ss as an array, and also use strncpy because it's a bit safer, in general.

char ss[10]; // This allocates 10 chars of space on the stack.
strncpy(ss, ss2, 10); // Do not copy more than 10 characters.

Upvotes: 2

Related Questions