【问题标题】:Getting segmentation fault with this code but I'm not sure how to fix it这段代码出现分段错误,但我不知道如何修复它
【发布时间】:2020-07-10 20:15:30
【问题描述】:

当我尝试使用例如这些数字运行程序时,出现分段错误:

17 56
2748 55539 ​​24890 4564
1995 44437 39060 75810
2583 49463 73827 24420
395 46500 56779 60559
273 30090 78489 37881
950 76442 92020 15157
756 85200 19627 13615
1787 79756 51484 34462
1424 65520 83527 74748
2738 10501 9678 95956
2250 92554 55640 91863
2402 84001 72097 92122
1223 71750 71493 12744
164 99321 73824 93276
1057 96262 24703 68502
1649 76765 48873 18181
2552 49371 32960 81865

我感觉它可能与 scanf 相关,但我不确定它是什么。

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>

int main(){
        int holes;
        int p;
        scanf("%d %d", &holes, &p);
        double plates = (double) p;
        int* R[holes];
        int* X[holes];
        int* Y[holes];
        int* Z[holes];
        double sizeOfPlate[p];
        for(int i = 0; i < holes; i++){
                scanf("%d %d %d %d", R[i], X[i], Y[i], Z[i]);
        }

        if(holes == 0){
                for(int i = 0; i < p; i++){
                        sizeOfPlate[i] = 100 / plates;
                }
                for (int i = 0; i < p; ++i)
                {
                        printf("%.9lf\n", sizeOfPlate[i]);
                }
        }
        else if(p == 1)
                printf("100.0000000");
        else{
                printf("Wrong result");
        }
        return 0;
}

【问题讨论】:

  • 您应该始终检查scanf 的返回值。您的输入可能会被一些剩余的'\n' 破坏,如果您不关心此返回值,您将永远不会注意到。

标签: c arrays pointers segmentation-fault scanf


【解决方案1】:

在您的代码中,

    int* R[holes];
    int* X[holes];
    int* Y[holes];
    int* Z[holes];

都是指针数组,但这些指针本身并不指向任何有效内存。除非这些数组中的每个指针都指向有效内存,否则将它们用作scanf() 的参数将导致undefined behaviour。分段错误是副作用之一。

你需要

  • 将这些指针指向一些有效的内存(像malloc() 这样的分配器函数)
  • 创建int 类型的数组而不是int *,然后使用每个元素的地址作为scanf() 的参数。

【讨论】:

  • 扩展此答案:执行此行时会发生段错误:scanf("%d %d %d %d", R[i], X[i], Y[i ], Z[i]);
猜你喜欢
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 2019-12-30
相关资源
最近更新 更多