C:rand()函数偶尔会导致分段错误

Ahm*_*ved 1 c linux segmentation-fault

给定下面是将随机整数存储在二进制文件中的代码.二进制文件的大小应该是65536字节,所以我必须生成总共16634个整数,然后一次保存16个整数.这已经在populateBackingStore()函数中实现.这里的问题是在线"有时"发生分段错误:

buffer [i%16] = rand ()  % MAX_INT;.
Run Code Online (Sandbox Code Playgroud)

注意:出于调试目的,我打印了迭代编号,我发现分段错误仅发生在第16358次迭代.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 7

int * buffer = (int* ) malloc (16);

你没有为16 ints 分配足够的空间.你要分配16个字节.

改成

int * buffer = malloc (16 * sizeof (*buffer));
Run Code Online (Sandbox Code Playgroud)

相关阅读:

  1. malloc() 手册页.
  2. 不要强制转换返回值malloc().