请看一下这段 C 代码。这是我写的一个小程序,它以数字n为输入,计算从2到n的所有质数。当 n<100 时它工作正常,但如果我输入 1000 或更多它会崩溃。我不明白为什么,因为存储数字的数组是动态分配的,所以内存不足应该不是问题。
那么,为什么程序会在大输入时崩溃?
此外,对于代码的可读性差,我深表歉意。我刚刚开始编程。
代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int n;
int *array = malloc((n-1)*sizeof array);
int q = 0;
int k;
int *array2;
printf("Geben Sie eine natuerliche Zahl n ein: ");
scanf("%d", &n);
printf("\n");
for(i=0; i<=n-2; i++){
array[i] = i+2;
}
while(q<=n-2){
while(array[q]==0&&q<=n-2){
q++;
}
for(i=q+1; i<=n-2; i++){
if(array[i]%array[q]==0){
array[i] = 0;
}
}
q++;
}
PART1:
for(i=0; array[i]!=0; i++){
if(array[i+1]==0){
int j;
for(j=i+1; j<=n-2; j++){
if(array[j]!=0){
array[i+1] = array[j];
array[j] = 0;
goto PART1;
}
}
k = i;
goto PART2;
}
}
PART2:
*array2 = malloc((k+1)*sizeof array2);
for(i=0; i<=k; i++){
array2[i]=array[i]; //Here's where the program crashes
}
free(array);
for(i=0; i<k; i++){
printf("%d ,", array2[i]);
}
printf("%d\n\n", array2[k]);
free(array2);
return 0;
}
codeblocks 调试器说:程序在第 53 行收到信号 SIGSEGV,段错误。我在代码中标记了它。
最佳答案
修复过程
- 使用调试器(总是)找到导致段错误的行
- 研究涉及的违规变量
在这种情况下,第 53 行指的是未正确分配的 array2
访问。
需要更改
- move allocation of array1 after the scanf has properly assigned n
- change the allocation of array2 which was previously assigning malloc return to the contents of the pointer array2 instead of array2 ( which at this stage was also unallocated ) pointer
- adjust allocation to use
sizeof(*array1+2)
as identified by @alk
调整后的代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, n, q = 0, k, *array2;
printf("Geben Sie eine natuerliche Zahl n ein: ");
scanf("%d", &n);
int *array = malloc((n-1)*sizeof(*array));
printf("\n");
for(i=0; i<=n-2; i++){
array[i] = i+2;
}
while(q<=n-2){
while(array[q]==0&&q<=n-2){
q++;
}
for(i=q+1; i<=n-2; i++){
if(array[i]%array[q]==0){
array[i] = 0;
}
}
q++;
}
PART1:
for(i=0; array[i]!=0; i++){
if(array[i+1]==0){
int j;
for(j=i+1; j<=n-2; j++){
if(array[j]!=0){
array[i+1] = array[j];
array[j] = 0;
goto PART1;
}
}
k = i;
goto PART2;
}
}
PART2:
array2 = malloc((k+1)*sizeof(*array2));
for(i=0; i<=k; i++){
array2[i]=array[i]; //Here's where the program crashes
}
free(array);
for(i=0; i<k; i++){
printf("%d ,", array2[i]);
}
printf("%d\n\n", array2[k]);
free(array2);
return 0;
}
另请参阅这篇关于实现 sieve of erastothenes
的文章在 c.
关于c - 程序在大量输入时崩溃 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30135713/