【发布时间】:2015-05-09 16:20:36
【问题描述】:
- 这里有一个很好的答案,Segfault in c++ program; Incomprehensible valgrind output,但它没有解释我的代码中发生了什么
错误总结:
==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