Home > Software engineering >  Scanf into pointer
Scanf into pointer

Time:03-16

I have this code:

char *ps = "hello";
scanf("%s", ps);

I want to write a string, let's pretend "a", to pointer without using an array. Trying to scanf a string into ps causes error interrupted by signal 10: SIGBUS. I'd be happy to hear an explanation for such a behavior.

CodePudding user response:

The pointer points to a string literal

char *ps = "hello";

So this call

scanf("%s", ps);

tries to change a string literal.

You may not change string literals. Any attempt to change a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

  • Related