malloc - C - writing buffer into a file then FREEing the buffer cause segfault -
i'm writing buffer binary file. code in following :
file *outwav = fopen(outwav_path, "wb"); if(!outwav) { fprintf(stderr, "can't open file %s writing.\n", outwav_path); exit(1); }
[...]
//create sample buffer short *samples = malloc((loopcount*(blockamount-looppos)+looppos) << 5); if(!samples) { fprintf(stderr, "error : can't allocate memory.\n"); exit(1); }
[...]
fwrite(samples, 2, 16*k, outwav); //write samplebuffer file fflush(outwav); fclose(outwav); free(samples);
the last free() call causes me random segfaults. after several headaches thought because fwrite call execute after delay, , read freed memory. added fflush call, yet, problem still occurs.
the way rid of not free memory , let os me. supposed bad practice though, i'd rather ask if there no better solution.
before asks, yes check file opened correctly, , yes test memory allocated properly, , no, don't touch returned pointers in way.
once fwrite
returns free whatever want buffer. can remove fflush
call.
it sounds buffer overflow error in totally unrelated part of program writing on book-keeping information free
needs work. run program under tool valgrind
find out if problem , find part of program has buffer overflow.
Comments
Post a Comment