I have a text adventure game in ANSI C that is trying to load a text file containing the area description from a .txt file into a heap allocated buffer, which is then copied into the area structs char* description variable.
while the below code executes OK, when I come to print the contents of area->description to the screen, it crashes with:
please can someone advise what may be wrong? I'm using 5000 bytes below just as an example, the file itself contains about 5 lines of text. (Visual Studio 2019, Windows 10)
I see the same two things that Ganado pointed out.
- You don't limit check i in your while loop.
- Since you're using malloc, you don't check for an error return from malloc.
Using the VS debugger, set a break point at line 21. Verify the value of i.
Set another breakpoint at line 23. Verify the value of area->description.
Thank you very much for the replies all, I've done some refactoring based on your comments to improve it :)
My apologies, but I wrongly assumed the posted code was the problem, when it wasn't. It turned out the "stack cookie check failure" occured when I tried to read/print area->description to the screen. But the code handling that was also correct. I replaced all 5 lines of text contained in the file with just "aaaaa" etc, and it worked fine. So the error seems to be caused by some formatting in the text file for some reason
also, consider testing small parts at a time. first, hard code a couple of strings and see if your bool function works. Then add applying it to a file, which you first read and validate that it read the file by printing to screen. Then apply the function to the data ... not much can go wrong now that you have 2 working pieces, but debugging 2 non working pieces is much harder...