简体   繁体   中英

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);
}

The only difference between malloc and calloc is that calloc initializes the memory to 0, and malloc doesn't initialize it.

So the bug might be that you are accessing somewhere some data that was overwritten with 0s by calloc . I would recommend that you check the lifecycle of the b buffer, or some other dynamically allocated data.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM