1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char * argv[])
{
    /*
        arguments from command line:
        N: dimension of each tuple
        M: maximum possible number of attributes
            a tuple can take
    */
    int N,M;
    N = atoi(argv[1]);
    M = atoi(argv[2]);

    // Ln store attribute range from 0 to Ln[i]-1;
    int * Ln = (int *)malloc(N);
    //int Ln[N];
    //printf("N: %d, M: %d\n",N,M);
    /*
        to generate parameters to file "repo_file.txt"
    */

    int i,seed,p1,p2,p3;
    seed = time(NULL);
    p1 = 762; p2 = 8196; p3 = 9765;
    for(i=0;i<N;i++)
    {
        seed  = (p1*seed+p2)%p3;
        srand(seed);
        Ln[i] = (rand()%M+1);
        printf("%dth element: %d \n",i,Ln[i]);
    }

   free(Ln);
   return 0;
}

上記のように、いくつかの乱数を配列に割り当てます。ただし、次のようなエラーが発生します。セグメンテーション違反(コアダンプ)、free()呼び出しが原因のようです。

4

2 に答える 2

7

正しいバイト数を割り当てていません:

 int * Ln = (int *)malloc(N);

N使用するバイト単位ですN * sizeof *Ln

また、補足として、mallocをキャストしないでください。

于 2012-09-17T19:46:29.737 に答える
2

Lnアレイに十分なスペースを割り当てていません。整数用のスペースではなく、N バイトのみを割り当てています。Nしたがって、ループは配列の終わりを通り過ぎます。

使用する:

int *Ln = malloc(N * sizeof(int));
于 2012-09-17T19:46:55.223 に答える