【问题标题】:C segmentation fault, invalid read of size 4C 分段错误,大小为 4 的无效读取
【发布时间】:2015-05-09 16:20:36
【问题描述】:

错误总结:

==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));

【问题讨论】:

  • 你的真实代码是否测试malloc()在这里是否失败:int_arr_ptr = malloc(arr_size * (sizeof(int)));
  • 您的代码看起来不错.. 都在main 中吗?如果没有,您能否包含调用设置和函数的代码?
  • int_arr_ptr 是“功能部分”中的NULL。我将继续猜测您在进行设置时忘记了 C 使用按值传递
  • @alk 在 malloc 之后有一个测试
  • @Batousik 调试您的代码并遵循int_arr_ptr 的值,看看它在哪里变成了NULL。为避免我们不得不猜测,您必须遵循代码发布指南here

标签: c segmentation-fault valgrind check-framework


【解决方案1】:

显然是命名函数

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多