S
Suraj Kurapati
Hello,
I'm having a rather strange bug with this code: for certain values of 'buf',
a segmentation fault occurs when 'free(buf)' is followed by an 'fwrite()'.
In the program output, there is no error reported by 'perror()' and the
file is written correctly.
/* returns NULL upon failure, or a calloc()ed data upon success */
char* recv_data(int *bytes_read);
int main(int argc, char** argv)
{
char *buf;
int bufLen;
FILE *fd;
/* ... some initialization code */
buf = recv_data(&bufLen); /* 'bufLen' has the length of 'buf' */
if(buf != NULL)
{
if(fwrite(buf, sizeof(char), bufLen, fd) <= 0)
perror("fwrite");
free(buf); /* segmentation fault occurs here */
buf = NULL;
}
return 0;
}
There is no crash when I remove the call to 'fwrite()', regardless of the
value of 'buf'. Thus I conjecture that 'fwrite()' is the culprit here.
Any ideas?
Thanks.
I'm having a rather strange bug with this code: for certain values of 'buf',
a segmentation fault occurs when 'free(buf)' is followed by an 'fwrite()'.
In the program output, there is no error reported by 'perror()' and the
file is written correctly.
/* returns NULL upon failure, or a calloc()ed data upon success */
char* recv_data(int *bytes_read);
int main(int argc, char** argv)
{
char *buf;
int bufLen;
FILE *fd;
/* ... some initialization code */
buf = recv_data(&bufLen); /* 'bufLen' has the length of 'buf' */
if(buf != NULL)
{
if(fwrite(buf, sizeof(char), bufLen, fd) <= 0)
perror("fwrite");
free(buf); /* segmentation fault occurs here */
buf = NULL;
}
return 0;
}
There is no crash when I remove the call to 'fwrite()', regardless of the
value of 'buf'. Thus I conjecture that 'fwrite()' is the culprit here.
Any ideas?
Thanks.