471,336 Members | 1,267 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,336 software developers and data experts.

Segmentation fault - fprintf

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 -
structure = b_function();
FILE *fout;
if((fout = fopen("test.dat", "w")) == NULL)
printf("can't open file.\n");
fprintf(fout, "testing\n");

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
1 4347
256 100+
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.

Similar topics

7 posts views Thread by Adi | last post: by
1 post views Thread by Dawn Minnis | last post: by
5 posts views Thread by Fra-it | last post: by
1 post views Thread by didier2309 | last post: by
6 posts views Thread by SP | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.