Char * p and scanf

I am trying to find the reason the following code is not working and I could not find it. So please excuse my ignorance and let me know what is going on here.

#include<stdio.h> int main(void){ char* p="Hi, this is not going to work"; scanf("%s",p); return 0; } 

As I understand it, I created a pointer p to an adjacent memory area of ​​size 29 + 1 (for \ 0). Why can't I use scanf to modify the content?

PS Please correct me. If I said something wrong about char *.

+6
c scanf
source share
4 answers
 char* p="Hi, this is not going to work"; 

it does not allocate memory for you to write

String Literal is created, which results in an Undefined Behaviour every time the content changes.

use p as a buffer for your scanf to do something like char * p = malloc(sizeof(char) * 128); // 128 is an Example char * p = malloc(sizeof(char) * 128); // 128 is an Example

OR

you also can:

 char p[]="Hi, this is not going to work"; 

I think this is what you really wanted to do.

Keep in mind that this can still be UB , because scanf() does not check if the location you are using is really writeable.

remember:

char * p is a string literal and should not be changed

char p[] = "..." allocates enough memory to store the string inside "..." and can be changed (its contents I mean).

Edit:

A good trick to avoid UB is

 char * p = malloc(sizeof(char) * 128); scanf("%126s",s); 
+14
source share

p indicates a constant literal, which may actually be in the read-only memory region (implementation dependent). Anyway, when trying to overwrite this undefined behavior . That is, it can lead to nothing, an immediate crash or hidden memory corruption that causes mysterious problems much later. Never do that .

+6
source share

This is a failure because memory was not allocated for p. Allocate memory for p and everything should be fine. What you have is a constant region of memory pointed to by p. When you try to write something in this data segment, the runtime will raise a trap that will crash.

Hope this answers your question.

0
source share

scanf() parses data entered with stdin (usually a keyboard). I think you want sscanf() .

However, the purpose of scanf() is to split the string with predefined escape sequences that your test string does not have. Thus, it is a little unclear what exactly you are trying to do.

Note that sscanf() takes an additional argument as the first argument, which indicates the line to be processed.

-3
source share

All Articles