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(&bufL en); /* '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. 15 3874
"Suraj Kurapati" <sk******@ucsc. edu> wrote in message
news:40abe3dc@d arkstar... 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(&bufL en); /* '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.
I conjecture that buf has no space allocated to it.
--
Mabden
Mabden wrote: I conjecture that buf has no space allocated to it.
Actually, this condition is checked by the statement "if(buf != NULL) {}".
Consider this:
if(buf != NULL)
{
free(buf); /* works fine */
}
As opposed to this:
if(buf != NULL)
{
if(fwrite(buf, sizeof(char), bufLen, fd) <= 0)
perror("fwrite" );
free(buf); /* segmentation fault occurs here */
}
Thanks.
In article <40abeaec@darks tar>, Suraj Kurapati <sk******@ucsc. edu> wrote: Mabden wrote:
Actually, this condition is checked by the statement "if(buf != NULL) {}".
That doesn't check that your function really allocated the space
correctly, of course.
There's clearly something going on that's not shown in the code you've
posted. Probably a malloc()/free() error somewhere else. I suggest
linking with a debugging version of malloc().
fwrite() itself may well call malloc(), which would explain why the
error only shows up when you call it.
-- Richard
Suraj Kurapati wrote: 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(&bufL en); /* '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 _really_ suspect your `recv_data()' function.
Since you say that only certain values of `buf'
cause this leads me to believe that you may
possibly be over-running `buf'. Consider
that, in general, `calloc()' will allocate
more space than is actually requested by
some small power of 2 (16, 32 bytes, etc.)
usually for efficiency of the algorithm/hardware, etc.
Lets assume your library allocates memory
blocks in multiples of 16 bytes.
If you request 15 bytes, you'll get 16 - I
think you see where I'm going with this.
If you're overwriting `buf' by a single
byte, you won't see a problem since it's
still within the buffer's limits.
But, on that occasion where you request 16,
and actually get exactly 16 (but actually need 17),
then that extra byte is corrupting the heap,
and your next call to `free()' seg faults.
That's my theory, and I'm sticking to it...
If `recv_data()' is small enough to post,
I'd suggest that. Since `fwrite()' is used
in billions of places, I _really_ doubt
there's a problem with `fwrite()'.
HTH,
Stephen
Suraj Kurapati wrote: 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.
/* ... some initialization code */
Please post COMPLETE programs. We have no idea what went on in this
section, especially whether that included allocating sufficient space to
your buffer. The symptom you describe is that of corrupted memory, such
as overrunning the bounds of a dynamically allocated array.
Brian Rodenborn
Richard Tobin wrote: fwrite() itself may well call malloc(), which would explain why the error only shows up when you call it.
Thanks, that did the trick.
By replacing the calls to fopen()/fwrite()/fclose() with
open()/write()/close(), the call to 'free(buf)' no longer crashes.
The latter set of system calls operate on an int, rather than a dynamically
allocated FILE struct (which was the source of the trouble).
On Wed, 19 May 2004, Suraj Kurapati wrote: Richard Tobin wrote: fwrite() itself may well call malloc(), which would explain why the error only shows up when you call it. Thanks, that did the trick.
By replacing the calls to fopen()/fwrite()/fclose() with open()/write()/close(), the call to 'free(buf)' no longer crashes.
open(), write(), and close() are none of them standard C functions.
You may know this already, of course, but you are sacrificing portability
by using them.
The latter set of system calls operate on an int, rather than a dynamically allocated FILE struct (which was the source of the trouble).
Wouldn't it be more responsible to fix *YOUR* mistake now, rather
than hacking around it without fixing it? If you really can't find
the source of the error, post some code and I'm sure the experts here
will be glad to show you where you went wrong.
-Arthur
Suraj Kurapati wrote: Richard Tobin wrote:
fwrite() itself may well call malloc(), which would explain why the error only shows up when you call it.
Thanks, that did the trick.
By replacing the calls to fopen()/fwrite()/fclose() with open()/write()/close(), the call to 'free(buf)' no longer crashes.
The latter set of system calls operate on an int, rather than a dynamically allocated FILE struct (which was the source of the trouble).
I think you're going to have a difficult task convincing
readers of comp.lang.c that the fopen()/fwrite()/fclose()
family of I/O functions are the culprit...
Stephen
Suraj Kurapati <sk******@ucsc. edu> wrote in message news:<40abe3dc@ darkstar>... 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(&bufL en); /* '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?
You probably have a bug in the code you haven't shown, either corrupting
buf or overrunning the end of the buffer that buf points to. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Antoine Bloncourt |
last post by:
Hello everybody
Sorry to bother you but I have a problem writing datas into a file ...
I want to make a backup of my MySQL database and put the result into a
..sql file.
To do this, I use the "get_table_strucure" and "get_table_content"
functions.
|
by: FrancisC |
last post by:
how to use fwrite( ) instead of fprintf( ) in this case? I want to generate
binary file.
FILE *fnew;
int i, intName;
double array;
fprintf(fnew, "%d\n", intName);
fprintf(fnew, " %f", array);
|
by: SW1 |
last post by:
I wrote a small program which does something like tftp - transfering
files and some chat, anyway i got a problem with fwrite, here is a
snippet of my code:
while(length > 0) {
putchar('.'); //These were for error checking
if(length <= bsize) { //Buffer is bigger than remaining File
realloc(buffer,length * sizeof(char)); //resize buffer
to remain
rec = recv(sock,buffer,length,0); //recieve Data
|
by: ibrahimover |
last post by:
typedef struct{
char name;
int no;
}TAM;
typedef struct{
char name;
char ch;
}HARF;
|
by: sumit1680 |
last post by:
Hi everyone,
I am using the below listed code
The code is
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
| |
by: janssenssimon |
last post by:
//de structure om de highscores in op de slagen
typedef struct score{
char *naam;
int veld;
int score;
struct score *volg;
}HIGH;
void toonhighscores(void)
|
by: Richard Hsu |
last post by:
// code
#include "stdio.h"
int status(FILE * f) {
printf("ftell:%d, feof:%s\n", ftell(f), feof(f) != 0 ? "true" :
"false");
}
int case1() {
FILE * f = fopen("c:\\blah", "wb+");
int i = 5;
|
by: hemant.gaur |
last post by:
I have an application which writes huge number of bytes into the
binary files which is just some marshalled data.
int len = Data.size(); //arrary size
for (int i = 0; i < len; ++i)
fwrite(&Data, 1, 1, f);
now after running this for long time and pushing millions of bytes, It
once misses writing the last byte of fData. Then the further push of
bytes is again correct. As i am not using the return value for the
|
by: Abubakar |
last post by:
Hi,
recently some C programmer told me that using fwrite/fopen functions
are not efficient because the output that they do to the file is
actually buffered and gets late in writing. Is that true?
regards,
...ab
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |