【问题标题】:Segmentation fault in a function函数中的分段错误
【发布时间】:2019-11-27 05:35:30
【问题描述】:

我想在一个数组中找到一个整数的地址。调试器显示第 8 行有问题。 if (*i==item) {ans=i;};

变量ans 是本地变量且不为空,但发生分段错误。 为什么会这样,我该如何解决?

#include <stdio.h>

int* finder(int *begin, int *end, int item)
{
    int *ans=0; int *i=begin;

    while (i<end) {
        if (*i==item) {ans=i;};
        i++;
    }

    return ans;
}

int main()
{
    int arSize, target, i=0;
    int arr[10]={};
    int *first=&arr[0]; int *last; int *result;

    printf("Find element: ");
    scanf("&d",&target);
    printf("Array size: ");
    scanf("&d",&arSize);
    printf("Enter array: ");
    while (i<arSize){
        scanf("&d",&arr[i]);
        i++;
    }

    last=&arr[arSize];
    result=finder(first,last,target);

    printf("%s %p","Target's address is ",result);


    return 0;
}

【问题讨论】:

  • ans 不是问题。更有可能是iarSize 的值是多少?请告诉我们确切的输入。
  • 这应该是 last=&arr[arSize-1] ....
  • 如果arSize10 或更多呢?如果为真,那么last=&amp;arr[arSize]; 会导致未定义的行为,因为您将访问数组元素越界。 B/w scanf("&amp;d",&amp;target); --> scanf("%d",&amp;target);
  • 你为什么用*ans而不是ans?你用这个声明一个数组。如果你也设置它NULL。您似乎多次这样做了。
  • 错字。 scanf() 调用使用格式字符串中的&amp;,而不是%。所以变量没有被读取。由于在使用它们的值时它们未初始化,因此代码具有未定义的行为。

标签: c gcc segmentation-fault


【解决方案1】:

scanf() 格式有错字:他们使用'&amp;' 而不是'%。结果,程序(如发布的)不会读取任何输入。

建议:确保在尝试运行(或调试)之前进行 CLEAN 编译(无警告、无错误)。 GCC 使用默认的“cc”标记格式错误。

ff.c:22:11:警告:格式参数过多 [-Wformat-extra-args]

 scanf("&d",&target);
       ^~~~

需要 3 个修复。

  • scanf("&amp;d",&amp;target);
  • scanf("&amp;d",&amp;arSize);
  • scanf("&amp;d",&amp;arr[i]);

例如:

    printf("Array size: ");
// BAD:    scanf("&d",&arSize);
    scanf("%d",&arSize);

通过此修复,代码似乎在简单情况下运行良好。

【讨论】:

  • 另外,在未确认成功之前,切勿使用scanf()(或其他输入函数)。在这种情况下,一个简单的if (scanf(...) != 1) 就会识别出错误。
【解决方案2】:

如果 arSize 等于 10,它可能会在 finder() 内部的最后一次迭代中失败。

你声明了一个数组'arr[10]',所以这意味着最后一个元素的索引等于9,而不是10:)

所以,你应该在 main() 中更改一行:

last=&arr[arSize];

到:

last=&arr[arSize-1];

当然,您应该始终检查 arSize 是否

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多