0

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;
Alessandro Baffa
  • 1,127
  • 3
  • 11
  • 25
  • 7
    `char *ss;` This is an uninitialized pointer, and writing to it is undefined behavior. – dxiv Jan 14 '21 at 01:21
  • 1
    If you always ask yourself "What valid memory does my pointer point to" (e.g. what address does my pointer hold as its value), you will eliminate 99% of your pointer problems. A few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) (ignore the titles, the answers discuss pointer basics) – David C. Rankin Jan 14 '21 at 03:17

2 Answers2

2

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.
Alex
  • 947
  • 6
  • 16
  • 2
    `strncpy` is a poor choice because it doesn't write a null terminator in some cases – M.M Jan 14 '21 at 01:37
  • recommend to use malloc for undetermined length of buffer as the following. **char* ss; ss = (char*)malloc(strlen(ss2)+1); strcpy(ss,ss2); ... ... ...; free(ss);** – Dong0321 Jan 14 '21 at 02:28
-1

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];
user123
  • 2,510
  • 2
  • 6
  • 20
  • 2
    ss isn't point to 0 it is unitialized... certain storage classes are implicitly initialized to 0... like global static, but inside a function it is likely going to be a garbage value. – Grady Player Jan 14 '21 at 01:28
  • That's probable. The rest remains true. Just replace 0 with garbage value in my answer. – user123 Jan 14 '21 at 01:37