Search code examples
cunixmalloccalloc

Calloc causes segfault but not malloc


I am implementing a ringbuffer and in one method I am reading CHUNKSIZE bytes from a file in a loop and insert the pointer into the ringbuffer.

I am doing this in a while loop. The code works fine with malloc but calloc causes a segfault at the end of the loop. This is really mysterious.

Here is the code:

fpos_t position = 0;
fpos_t file_size = 0;
fseek(file, 0L, SEEK_END);
fgetpos(file,&file_size);
fseek(file, 0L, SEEK_SET);
char* b = calloc(CHUNKSIZE,sizeof(char));
// char* b = malloc(sizeof(char)*CHUNKSIZE);
while(fread(b,1,CHUNKSIZE,file)){
    deposit(reader_buf,b);
    // This always changes the cursor position by -150 to create overlapping chunks
    fseek(file,-150,SEEK_CUR);
    b = calloc(CHUNKSIZE,sizeof(char));
    // b = malloc(sizeof(char)*CHUNKSIZE);
}

Solution

  • It's probably not that malloc segfaults and calloc doesn't. To prove this, put a diagnostic puts( "allocated memory" ); after the malloc-or-calloc line and try it again. Throw another right after the loop. That should prove to you that it is not the choice of function itself that is causing the problem.

    Try using a run-time memory debugger like valgrind. I wouldn't be surprised if it finds your problem on the first time your run your program with it. I also would not be surprised if it turns out that you were relying on zeroed out memory like Alexandru C. suggests.