[英]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.
但是,我得到如下错误:分段错误(内核已转储),似乎是由于free()调用引起的。
You are not allocating the correct amount of bytes: 您没有分配正确的字节数:
int * Ln = (int *)malloc(N);
N
is in bytes you should use N * sizeof *Ln
N
为字节,应使用N * sizeof *Ln
And as a side note, do not cast malloc . 另外, 请不要强制转换malloc 。
You aren't allocating enough space for the Ln
array. 您没有为
Ln
数组分配足够的空间。 You're only allocating N
bytes , not space for N
integers. 你只是分配
N
个字节 ,不空间N
整数。 So your loop will walk past the end of the array. 因此,您的循环将经过数组的末尾。
Use: 采用:
int *Ln = malloc(N * sizeof(int));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.