I have been trying to look for a reason why the following code is failing, and I couldn't find one.
So please, excuse my ignorance and let me know what's happening here.
#include<stdio.h>
int main(void){
char* p="Hi, this is not going to work";
scanf("%s",p);
return 0;
}
As far as I understood, I created a pointer p to a contiguous area in the memory of the size 29 + 1(for the \0).
Why can't I use scanf to change the contents of that?
P.S Please correct me If I said something wrong about char*.
char* p="Hi, this is not going to work";
this does not allocate memory for you to write
this creates a String Literal
which results inUndefined Behaviour
every time you try to change its contents.
to use p
as a buffer for your scanf
do something like
char * p = malloc(sizeof(char) * 128); // 128 is an Example
OR
you could as well do:
char p[]="Hi, this is not going to work";
Which I guess is what you really wanted to do.
Keep in mind that this can still end up being UB
because scanf()
does not check whether the place you are using is indeed valid writable memory.
remember :
char * p
is a String Literal and should not be modified
char p[] = "..."
allocates enough memory to hold the String inside the "..."
and may be changed (its contents I mean).
Edit :
A nice trick to avoid UB
is
char * p = malloc(sizeof(char) * 128);
scanf("%126s",s);
p
points to a constant literal, which may in fact reside in a read-only memory area (implementation dependent). At any rate, trying to overwrite that is undefined behaviour. I.e. it might result in nothing, or an immediate crash, or a hidden memory corruption which causes mysterious problems much later. Don't ever do that.
It is crashing because memory has not been allocated for p. Allocate memory for p and it should be ok. What you have is a constant memory area pointing to by p. When you attempt to write something in this data segment, the runtime environment will raise a trap which will lead to a crash.
Hope this answers your question
scanf()
parses data entered from stdin (normally, the keyboard). I think you want sscanf()
.
However, the purpose of scanf()
is to part a string with predefined escape sequences, which your test string doesn't have. So that makes it a little unclear exactly what you are trying to do.
Note that sscanf()
takes an additional argument as the first argument, which specifies the string being parsed.