EDIT: To answer some questions, this is the revised and still not working code (most of it was there to begin with, but I should have been explicit that I initialised the file pointer, etc). Again, only works if I either add a write before the exp() or remove the exp() entirely:
FILE *outfile;
char *outfilename;
outfilename = (char *)malloc(FILENAME_MAX*sizeof(char));
strcpy(outfilename, "outfile.txt");
outfile = fopen(realoutfilename, "w");
/* If this is uncommented, there isn't a segfault
if(realoutfile!=NULL && imoutfile!=NULL){
fprintf(outfile, "\r\n");
fseek(outfile,0,SEEK_SET);
}
*/
gauss = (double*) calloc(points, sizeof(double));
/* Maths and stuff */
if(outfile!=NULL){
for(i=0;i<points;i++){
/* this prints fine */
printf(outfile, "%g,\r\n", gauss[i]);
/* Seg fault is here */
fprintf(outfile, "%g,\r\n", gauss[i]);
}
}
fclose(outfile);
free(outfile);
And I'm compiling with:
gcc main.c -lm -Wall -Wextra -Werror -Wshadow -g -o main
To clarify, it doesn't reach the end of the function - so it's not the freeing that it crashes on. The crash is when it tries to write to the file in that for loop.
I've checked that exp() isn't over or underflowing, as I say, I can printf the output, but file writing is a no-no. It also fails if I try a simple call, say exp(2).
The gdb backtrace is (I'm not that familiar with gdb, thought it might help):
#0 0xff15665c in _malloc_unlocked () from /lib/libc.so.1
#1 0xff15641c in malloc () from /lib/libc.so.1
#2 0xff1a8c80 in _findbuf () from /lib/libc.so.1
#3 0xff1a8f0c in _wrtchk () from /lib/libc.so.1
#4 0xff1ad834 in _fwrite_unlocked () from /lib/libc.so.1
#5 0xff1ad798 in fwrite () from /lib/libc.so.1
#6 0x000128ac in gaussian ()
#7 0x00010f78 in main ()
Any help would be greatly appreciated!
The problem, is here:
outfilename = (char *)malloc(FILENAME_MAX*sizeof(char));
outfilename = "file.txt";
You can't assign a string like that, you have to use strcpy
:
strcpy(outfilename, "file.txt");
What's happening is that you're are overwriting the outfilename
pointer with the string assignment. Then you try to free it free(outfilename);
. Since you are freeing a string literal, the behavior is undefined, hence the crash you are getting.
As for why it crashes in one case and not the other. The behavior is undefined, therefore anything is allowed to happen. It's possible that your exponential function code does something to the stack/heap that could be causing it crash/not crash.
EDIT : I hope it's just a typo or mis-copy, but I also don't see where outfile
is initialized. If it really is never initialized, then that's the other error. (and most likely the one that's causing your particular segfault)
So it should look like this:
FILE *outfile;
outfilename = (char *)malloc(FILENAME_MAX*sizeof(char));
strcpy(outfilename, "file.txt");
outfile = fopen(outfilename, "w");
if (outfile == NULL){
// Error, file cannot be openned.
}