2

我使用 valgrind 来验证我的代码,它在我的一个函数中报告“条件跳转或移动取决于未初始化的值”,该函数将指针数组作为参数。

现在,如何在运行时检查数组是否包含垃圾值(可能正在使用条件断点)?说,我不访问指针,因此程序不会中断。

识别垃圾指针的检查条件是什么?

4

4 回答 4

3

While the other answers are correct, you can also get valgrind to help you identify which entry or entries in the array exactly are causing the problem.

What you need to do is to add code to your program which loops over the array (you may already have such a loop of course) and then include valgrind/memcheck.h and add something like this to the loop:

if (VALGRIND_CHECK_VALUE_IS_DEFINED(entry)) {
  printf("index %d undefined\n", index);
}

where entry is the actual value from the array and index is the index of that value in the arry.

于 2012-09-14T09:29:09.967 回答
2

您无法区分有效指针和垃圾(未初始化)指针,它们都只是数字。

您在代码中的某个点处理“垃圾”指针这一事实表明,在到达该点之前存在问题。

于 2012-09-12T10:11:53.357 回答
1

您需要系统地将所有指针初始化为 NULL。当您释放内存时,您的指针也会重置为 NULL。例如,这可以使用包装 malloc/free 的“构造函数/析构函数”函数来完成。只有这样,您才能测试 NULL 值指针以查看是否出现问题。

于 2012-09-12T10:19:43.600 回答
1

您不测试垃圾,而是在创建数组和第一次考虑使用这些值之间的某个时间点将非垃圾值放入数组中。通常你在创建数组时这样做:

const char* strings[] = {0, "junk", "here"};
int some_values[10] = { 0 };

Valgrind 使用自己的技巧来识别它认为是垃圾的东西,但这些技巧超出了标准的范围,常规的 C 代码不能使用它们(或者无论如何不应该尝试)。即使你能以某种方式挂钩 valgrind 所做的事情,你最终会得到不适用于所有实现的代码,或者只能在 valgrind 下运行的代码。

于 2012-09-12T10:20:52.343 回答