Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C String Pointers

Tags:

c

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);


}
like image 358
kuan Avatar asked Aug 30 '26 21:08

kuan


1 Answers

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

like image 165
Dylan Kirkby Avatar answered Sep 01 '26 13:09

Dylan Kirkby