Reputation: 19
Given Below is the code which stores random integers in a binary file. The size of the binary file should be 65536 bytes, so I have to generate total 16634 integers and then save them 16 integers at a time. This is has been implemented in populateBackingStore() function. The Problem here is that a segmentation fault occurs "sometimes" at line:
buffer [i%16] = rand () % MAX_INT;.
Note: For debugging purpose I have printed the iteration number and I have found that the segmentation fault only occurs at 16358th iteration.
#include <stdio.h>
#define BACKING_STORE 65536
#define MAX_INT 42949678295
int populateBackingStore () {
FILE * backingStore = fopen ("BACKING_STORE.bin", "wb");
int num, i;
int * buffer = (int* ) malloc (16); // 64 * (4 bytes) = 256 bytes
if (backingStore == NULL) {
printf ("Error while creating file BACKING_STORE.bin\n");
return NULL;
}
srand (time (NULL));
for (i = 0; i < BACKING_STORE/sizeof (int) ;i ++) {
buffer [i%16] = rand () % MAX_INT;
if ( i % 16 == 0 ) {
fwrite (buffer, sizeof (int), 16, backingStore);
}
printf ("%d ", i);
}
fclose (backingStore);
}
int main () {
populateBackingStore ();
return 0;
}
Upvotes: 1
Views: 2951
Reputation: 134276
int * buffer = (int* ) malloc (16);
You're not allocating enough space for 16
int
s. You're allocating 16 bytes.
Change to
int * buffer = malloc (16 * sizeof (*buffer));
Related reading :
malloc()
man page.malloc()
.Upvotes: 7