Reputation: 455
why is it not possible for sscanf() to write the string into char* s? I initialised it to NULL as I do not want uninitialised variables.
#include <stdio.h>
#include <string.h>
int main()
{
char* t = "I am a monkey";
char *s = NULL;
sscanf(t, "%s",s);
printf("%s\n",s);
}
Upvotes: 3
Views: 122
Reputation: 151
why is it not possible for sscanf() to write the string into char* s? I initialised it to NULL
The string functions in the C standard library do not allocate storage. All they do is copy things around. You have to manage every byte of string storage yourself. This will seem strange to someone coming from pretty much every other language.
In other words, you have to point *s to some memory for sscanf to write into. If you use NULL then sscanf writes to memory that starts at address NULL (usually 0).
Upvotes: 0
Reputation: 1427
The line char *s = NULL
creates a variable that holds the memory address of a character. Then it sets that memory address to zero (NULL
is address zero).
Then the line sscanf(t, "%s",s);
tries to write the contents of t
to the string at the location s
. This will segfault because your process cannot access address zero.
Your instincts were good to avoid uninitialized variables, but you traded this for unallocated pointers!
Fix this by allocating some space on the stack (or heap) for s by declaring:
char s[STRING_LENGTH];
Where STRING_LENGTH
is #defined
to be however many characters you want to allocate. This allocates a chunk of memory to hold the null-terminated character array and sets s
to the address of the first character
Upvotes: 8
Reputation: 27240
Here sscanf defination says that,,,
int sscanf ( const char * s, const char * format, ...);
sscanf(t, "%s",s);
So here it will take text from source as t
but on destination side s is just pointer to Null
there is no memory.
So allocate some memory to s using malloc
or assign s
to some valid memory location.
Upvotes: 1