C 段错误,大小为 4 的读取无效

C segmentation fault, invalid read of size 4

错误摘要:

==6520== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
==6520== 
==6520== 1 errors in context 1 of 1:
==6520== Invalid read of size 4
==6520==    at 0x401882: test_START_EMPTY_TREE_TREEBASE_PRINT_FREETREE_TEST (check_test.c:173)
==6520==    by 0x4046B2: srunner_run_all (in /home/travis/build/batousik/Practical-C2/bin/.libs/lt-check_test)
==6520==    by 0x4019EF: main (check_test.c:341)
==6520==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

设置:

 int_arr_ptr = malloc(arr_size * (sizeof(int)));
 ptr_tree_base_int_1 = new_base(comp_ints, clean_ints, print_ints);
 if(!ptr_tree_base_int_1 || !int_arr_ptr) {
    printf("Error allocating memory in test Setup\n");
    fflush(stdout);
    assert(NULL);
}
for (int i = 0; i < arr_size; ++i) {
    int r = rand() % 20000;
    *(int_arr_ptr+i) = r;
    printf("setup::%d\n",*(int_arr_ptr + i));
    fflush(stdout);
}

函数部分:

    int *ptr_helper;
    for (int i = 0; i < arr_size; ++i) {
        ptr_helper = malloc(sizeof(int));
        if (!ptr_helper)
            ck_abort_msg("FAILED memory allocation\n");
        printf("%d\n",*(int_arr_ptr + i));
        fflush(stdout);
        //*ptr_helper =
        isValid = insert(ptr_tree_base_int_1, ptr_helper);
        ck_assert_int_eq(isValid, true);
    }

拆解:

if (ptr_tree_base_int_1){
    isValid = freeTree(ptr_tree_base_int_1);
    ck_assert_int_eq(isValid, true);
    free(ptr_tree_base_int_1);
    ptr_tree_base_int_1 = NULL;
}
if(int_arr_ptr){
    free(int_arr_ptr);
    int_arr_ptr = NULL;
}

第 173 行是:

printf("%d\n",*(int_arr_ptr + i));

显然是在命名函数

void setup(void);
void teardown(void); 

void setup_x(void);
void teardown_x(void);

不同的名称并将此行添加到 main()

tcase_add_checked_fixture(tc_core, setup_x, teardown_x);

解决问题。

API: http://check.sourceforge.net/doc/doxygen/html/check_8h.html

参考:http://check.sourceforge.net/doc/check_html/check_4.html#Test-Fixtures