'Memory leak? Strange characters writing to file
Good Morning. This kinda ties in to a question I posted a few days ago, this is sort of a smaller example that all ties in. When I write the contents of array b to a text file it prints a bunch of strange characters. I'm new to C, and I'm also a student so I'm trying to learn a brand new language under a time constraint.
int main(int argc, char *argv[])
{
char a[3][10] = {"Apple", "Giraffe", "Boat"};
char b[4][10];
for(int i = 0; i < sizeof(a)/sizeof(a[0]); i++)
{
char tmp[15];
sprintf(tmp, a[i]);
sprintf(b[i], tmp);
}
FILE *f = fopen(argv[1], "wb");
fwrite(b, 15, sizeof(b), f);
fclose(f);
}
And this is a piece of the output that was written to the text file
Apple Giraffe 2€Boat q€ ¶¤6€ Apple Giraffe Boat H
Was it that I'm doing wrong that's causing this output? Should I be using memset? Malloc? Null terminators? Please help, thank you.
Solution 1:[1]
fwrite's signature is:
size_t fwrite(const void *restrict ptr, size_t size, size_t nmemb,
FILE *restrict stream);
sizeis the size of each item to writenmembis how many items you'd like to write
So, your call
fwrite(b, 15, sizeof(b), f);
will write sizeof(b) (4*10 => 40) items of size 15. That's 600 bytes and b is only 40 bytes. Since that's out of bounds for b, your program will have undefined behavior.
Also note that you haven't initialized b so it can contain just about anything. Either zero initialize it:
char b[4][10] = {0};
or set every character to a character you like:
char b[4][10];
memset(b, '*', sizeof b); // #include <string.h>
then write sizeof b items of size 1:
fwrite(b, 1, sizeof b, f);
or write 1 item of size sizeof b:
fwrite(b, sizeof b, 1, f);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
