Could anyone tell me what am i doing wrong over here? Why does my program segfault ?
I am trying to insert a third string between string1 and string2.
#include <stdio.h>
int main (void)
{
char *string1 = "HELLO";
char *string2 = "WORLD";
char *stringX = "++++";
char *string3;
printf ("%s,%s\n",string1,string2);
sprintf(string3,"%s%s%s",string1,stringX,string2);
printf ("NewVar: %s",string3);
}
Why doesn't sprintf store the resultant value at the memory address pointed by string3? It works when i declare string3 as an ordinary array but not when its a pointer to char array.
I thought string3 wasnt pointing to any memory location, but it does seem to when i do printf("%p",string3);
Output:
# ./concat
HELLO,WORLD,0x40042
string3is not pointing to any meaningful memory address. Its value is indeterminate and technically is not memory address at all. It might "seem" to point "to a memory location" but in reality this is just an illusion - a consequence of undefined behavior.