简体   繁体   中英

Segmentation fault (core dumped) when free an array

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

I am going to assign some random numbers to a array as coded above. However, I get the error like: segmentation fault (core dumped), seems it's caused by the free() call.

You are not allocating the correct amount of bytes:

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

N is in bytes you should use N * sizeof *Ln

And as a side note, do not cast malloc .

You aren't allocating enough space for the Ln array. You're only allocating N bytes , not space for N integers. So your loop will walk past the end of the array.

Use:

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

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