【问题标题】:Why does this code produce a bus error? (C Language)为什么此代码会产生总线错误? (C 语言)
【发布时间】:2017-03-13 01:54:30
【问题描述】:

我正在编写一个给我以下错误的函数:

/bin/sh: line 1: 15039 Bus error: 10           ( test/main.test )
make: *** [test] Error 138

我必须查一下什么是总线错误,显然是因为函数试图访问一个不存在的地址?我一直在查看这个相对较短的函数,但看不到发生了什么。

#include <stddef.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

#include "../include/array_utils.h"

int array_new_random(int **data, int *n)
{
    int i;
    srand(time(NULL));
    if(*data == 0){
        *data = malloc(*n * sizeof(int));
    }
    for(i = 0; i < n; i++){
        *data[i] = rand();
    }
    return n;
}

这是调用它的函数。

void test_array_new_random(void)
{
    int *buffer = NULL;
    int len = 100;
    int ret;

    t_init();
    ret = array_new_random(&buffer, &len);
    t_assert(len, ret);
    t_assert(100, len);

    free(buffer);
    t_complete();
}

这里还有一些其他已被调用的函数。我不认为它们那么重要,因为代码似乎在到达它们之前就崩溃了,但我可能错了。

void t_assert(int expected, int received)
{
    if (expected != received) {
        snprintf(buffer, sizeof(buffer), "EXPECTED %d, GOT %d.", expected, received);
        t_fail_with_err(buffer);
    }
    return;
}

void t_init()
{
    tests_status = PASS;
    test_no++;
    printf("STARTING TEST %d\n", test_no);
    return;
}

void t_complete()
{
    if (tests_status == PASS) {
        printf("PASSED TEST %d.\n", test_no);
        passed++;
    }
}

void t_fail_with_err(char *err)
{
    fprintf(stderr, "FAILED TEST %d: %s\n", test_no, err);
    tests_status = FAIL;
    tests_overall_status = FAIL;
    return;
}

因为我似乎正在编写一个通过测试的函数,所以你可能猜对了,这是一个家庭作业。

编辑:所以,一个问题是我使用了*data[i],而我应该使用(*data)[i]。但是,我现在收到此错误:

/bin/sh: line 1: 15126 Segmentation fault: 11  ( test/main.test )
make: *** [test] Error 139

【问题讨论】:

  • *data[i] 访问越界。你的意思可能是(*data)[i]
  • 你还在那个函数中混淆了n*n——如果编译器没有报告这个,那么你需要调整你的编译器设置
  • 是的;当 i &gt; 0data[i] 不指向任何分配的内存
  • for(i = 0; i &lt; n; i++){ (*data)[i] = rand(); } return n; --> for(i = 0; i &lt; *n; i++){ (*data)[i] = rand(); } return *n;
  • 请将其提炼成minimal reproducible example

标签: c bus-error


【解决方案1】:

您需要像这样进行更改,才能按预期工作

#include <stddef.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

#include "../include/array_utils.h"

int array_new_random(int **data, int *n)
{
    int i;
    srand(time(NULL));
    if(*data == 0){
        *data = malloc(*n * sizeof(int));
    }
    for(i = 0; i < *n; i++){   //Changed
        (*data)[i] = rand();   //Changed
    }
    return *n;                 //Changed
}

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 2016-03-29
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多