I copied some code that simply reads a file to a string and prints the string from an older program. It was working fine, so I decided to modify it a bit. The new program is
#include <stdio.h>
#include <string.h>
int main() {
FILE *itemlist = fopen("itemlist", "r");
char *currentstring, charbuffer[2];
// char itemstart = 0;
while (fgets(charbuffer, 2, itemlist)) {
strcat(currentstring, charbuffer);
}
printf("%s", currentstring);
return 0;
}
And it works as expected. But when I uncomment the itemstart line, it gives a segmentation fault. I’m not even using it and as far as I’m concerned, initializing an char to 0 is not illegal. I thought it was an issue with types, then I changed it to a short and then to int and it was still giving a segfault.
But then I removed the = 0 part and it worked again. Then I decided to put it back, debug the binary with gdb, and the segfault was at strcat.
How is this possible?
currentstringis a dangling pointer, sostrcat(currentstring, charbuffer);results in undefined behavior.Probably uncommenting
char itemstart = 0initializes some memory to0and the access violation is made visible, however this is just a guess. Undefined behavior means anything can happen.You should allocate memory for
currentstring: