By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,797 Members | 1,848 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,797 IT Pros & Developers. It's quick & easy.

Segmentation fault - fprintf

P: 1
Hi all,

Need some help in c. I have not been in programming for ten years. Here is my problem:
From main(), I call a function - a_function(). In a_function(), I call another function b_function() and then I allocate memory for a structure using calloc() in b_function(). Data is then copied to the structure. Structure is then return to the calling function which is a_function(). I then open a file for writing and then use fprintf() to write to the opened file. When I did all this, I get segmentation fault at the fprintf() statement. A very simple write statement -
a_function()
{
structure = b_function();
FILE *fout;
if((fout = fopen("test.dat", "w")) == NULL)
printf("can't open file.\n");
fprintf(fout, "testing\n");
fclose(fout);
}

structure_pointer *b_function()
{
declare structure pointer;
allocate memory for the structure;
copy the data;
return structure pointer;
}
I did check the file pointer and it is ok. memory allocation is ok. copy the data is ok. structure point return is ok.
If I open the file before b_function() and write to the file, there is no problem.

Thanks all ....
Jun 8 '07 #1
Share this Question
Share on Google+
1 Reply


100+
P: 256
Just a guess, but maybe something in b_function() is mangling your program memory in a way you haven't considered. Perhaps your memory copy step is faulty. I once had a piece of code that managed to mangle my program's call stack causing it to crash at seemingly benign places.

I'd run a debugger and look at everything stack, heap, local memory, etc starting from before you go into b_function()
Jun 8 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.