c - 相同代码的段错误

标签 c pointers segmentation-fault

<分区>

我有一个案例,我使用两组不同的变量调用了一个函数两次。第一次调用导致段错误,第二次调用成功返回。

除了变量名之外,参数完全相同。这种行为的原因可能是什么?

#include <stdio.h>
#include <stdlib.h>
#include "euler-v2.h"

#define POWER 1000

int main(void)
{
    int i;

    int base[] = { 2 };
    int *r;
    int *rlength;

    // The below line causes a segmentation fault
    r = power_arr(base, sizeof(base) / sizeof(int), 2, rlength);

    int n[] = { 2 };
    int *pow;
    int *length;

    pow = power_arr(n, sizeof(n) / sizeof(int), 2, length);


    exit(0); 
}

单独头文件中的函数原型(prototype):

int *power_arr(int *n, int nlength, int exp, int *res_length);

我看不出第一次调用 power_arr 和第二次调用有什么区别。是否了解这里到底发生了什么?

编辑:

函数 power_arr 的源代码:

int *power_arr(int *n, int nlength, int exp, int *res_length)
{
    int i, j, tmp_length;
    int *res, *tmp;

    res = n;

    printf("Step 1\n"); // Last printed line
    *res_length = nlength;
    printf("Step 2\n"); // Never reaches here

    while (--exp > 0)
    {
        tmp_length = *res_length;
        tmp = malloc(sizeof(int) * tmp_length);

        if (!tmp)
        {
            return NULL;
        }

        copy(tmp, res, *res_length);

        for (i = *n - 1; i > 0; i--)
        {
            res = sum(res, *res_length, tmp, tmp_length, res_length);
        }

        if (!res)
        {
            return NULL;
        }

            free(tmp);
    }
        return res;
}

请注意,我已将 printf 语句用于调试。我已经评论了代码执行失败的地方。

最佳答案

程序具有未定义的行为,因为指针 rlength 未初始化且具有不确定的值。

int *rlength;

另一方面,在您尝试使用此指针写入未分配内存的函数中。

*res_length = nlength;

关于c - 相同代码的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33928522/

相关文章:

c - C 中带有 char* 数组的 scanf 段错误

c - 如何将数组分成 block

c - 有没有一个示例如何捕获当我用鼠标右键单击任务栏上的图标时的事件?

c - C 变量的内存地址

c - 进程在 C 中返回 -1073741819 (0xC0000005)

c - 在 C 中 malloc 一个巨大的数组

c - 将指向指向 int 的指针的指针转换为指向指向 double 的指针的指针是否正确?

c - 如何优化分配固定红利?

php - 为什么脚本(动态)语言没有指针?

c - C中使用Malloc正确分配二维数组