2017-03-13 100 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 
} 
相關問題