I am not so clear on character pointer and how they work.
The program builds, but crashes when I run it.
char *ab = NULL;
//ab = "abc123"; // works fine
sprintf(ab, "abc%d", 123); // this line seems to crash the program
I don’t get how this can be wrong, when sprintf takes in a (char * str) as a first argument.
Can anyone please explain this to me?
You have allocated no memory to use with
ab.The first assignment works because you are assigning to
aba string constant:"abc123". Memory for constant strings are provided by the compiler on your behalf: you don’t need to allocate this memory.Before you can use
abwith e.g.sprintf, you’ll need to allocate some memory usingmalloc, and assign that space toab:Then your
sprintfwill work so long as you’ve made enough space usingmalloc. Note: the+ 1is for the null terminator.Alternately you can make some memory for
abby declaring it as an array:Without allocating memory somehow for
ab, thesprintfcall will try to write toNULL, which is undefined behavior; this is the cause of your crash.