Help coding in C?
This is a small part of the full program but basically I'm supposed to be able to load a string from a file and add a string to the end of that. If there's no string already loaded into the program, i should be able to add the string. Adding the string with nothing loaded, I'm having trouble allocating the memory. When I print the string, it doesn't have the last letter saved in memory. I honestly have no idea what I'm doing and I keep messing around with it. Please help. I can attach more pictures/info if needed.
- husoskiLv 72 months agoFavorite Answer
I can see a couple of oddities, one of them an outright bug.
In the else clause where you copy the filenames string into a newly allocated loaded string, you have strlen(filenames + 1) instead of strlen(filenames) + 1. That will be two characters too short, or a potential disaster if the filenames string is empty. (Yes, it can happen if there was a zero byte already at the beginning of filenames before the scanf(), and you hit end of file on the scanf() call.)
Other things I wouldn't put in a program include use of an unguarded %s in a scanf() string. You know there's room for 50 characters (plus a zero terminator byte), right? So use scanf("%50s") to make sure that no more than 50 characters get stored in the string.
You have added + 2 to the sum of the lengths of the strings you're concatenating instead of + 1. No harm done here, but there's only going to be one terminating zero byte in the final string.
You're calling strlen(filenames) multiple times. Maybe some new hotshot whole-program-optimizer can spot that and save the length; but it's not guaranteed. Again, no harm done, but probably some CPU cycles being wasted.
If you're not worried about performance, then--since you've made sure there's room in the receiving string--you could use strcpy() and strcat() to copy or append to the loaded string and save yourself some pointer arithmetic. Those are *only* safe if you've done those length checks in advance; so your instructor may not want to teach those functions.
Don't worry about this right now, but in serious code you should check the return values of every scanf(), malloc() and realloc().
I can't tell without seeing the input and output, and the rest of the code, whether these are causing any problems; but you absolutely must fix that strlen() bug mentioned at the top.