sprintf() and free()

Hello all

I've been trying to understand this but I just can't so I turn to you for help. I will leave most of the code out, so if you need me to post more code just tell me.

The code:
1
2
3
4
5
6
7
8
9
10
11
12
buf = (char *)calloc(len, sizeof(char));

for (i = 0; i <= k; i++)
{
    sprintf(&buf[strlen(buf)], ":%d  ", tokens[i].line);
    strcat(buf, tokens[i].word);
    strcat(buf, "\n");
}

fputs(buf, f);
fclose(f);
free(buf);



The problem:
I randomly (2/3 of the time) get an exception on the line free(buf); and the link seems to be with the sprintf(&buf[strlen(buf)], ":%d ", tokens[i].line); because commenting out either of them solves the problem.

I just don't see what I'm missing.

Thank you for you time and help.

EDIT: source of the whole function -> http://pastebin.com/Q1TJPM77
Last edited on
No doubt you're overrunning that buffer. Use the function versions that take a length.
1
2
3
4
5
6
7
8
9
10
11
12
buf = (char *)calloc(len, sizeof(char));

for (i = 0; i <= k; i++)
{
    snprintf(&buf[strlen(buf)], len - strlen(buf), ":%d  ", tokens[i].line);
    strncat(buf, tokens[i].word, len - 1);
    strncat(buf, "\n", len - 1);
}

fputs(buf, f);
fclose(f);
free(buf);


or C++ streams.
1
2
3
4
5
6
7
8
9
10
11
std::stringstream os;
for (i = 0; i <= k; i++)
{
    os << ":" << tokens[i].line
         << "  " << tokens[i].word
         << "\n";
}

std::string str = os.str();
fputs(str.c_str());
fclose(f);
Hot damn!

Thank you very much, I don't think I'd figure this one out for probably about a week.

Nice lesson, I see I have to take much bigger care about my calloc's and malloc's.

Thanks again kbw!
Last edited on
Topic archived. No new replies allowed.