2

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);
}
muxamilian
  • 342
  • 2
  • 11
  • 3
    What is the value of `CHUNKSIZE`? What does deposit() do with the buffer pointed to by b? Note that as is, this is one big memory leak since you never free b. – Jens Dec 21 '12 at 12:58
  • most probably your error is elsewhere, perhaps inside of `deposit`. In any case you don't show us enough to say anything. But then also, that type of question is not very appropriate for SO, this is not a code review site but a site for technical Q&A. – Jens Gustedt Dec 21 '12 at 13:01
  • I suspect that the calloc is wiping out a pointer, that malloc leaves alone. – kdubs Dec 21 '12 at 13:10
  • `CHUNKSIZE` is 1000, but I think it doesn't matter. b is freed in another thread. It wasn't intended as code review, I just thought I did miss some difference between `calloc` and `malloc` – muxamilian Dec 21 '12 at 13:19

2 Answers2

3

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.

Alexandru C.
  • 3,337
  • 1
  • 25
  • 27
1

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.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152