2017-03-13 101 views
-1

我正在写是给我下面的错误的函数:这段代码为什么会产生总线错误? (C语言)

/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 
+4

'*数据[I]'访问出界。你可能是指'(* data)[i]' –

+3

你也在这个函数中混用了'n'和'* n' - 如果编译器没有报告这个,那么你需要调整你的编译器设置 –

+0

@MM啊, 这就说得通了。猜猜我搞砸了符号。我尝试使用'n'的指针,但是编译器给了我一个错误,但这可能与我乱七八糟的符号有关。我猜''data [i]'返回'data [i]'指向的值? – Clotex

回答

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 
} 
相关问题