سؤال

I use valgrind to validate my code and it reports "Conditional jump or move depends on uninitialised value(s)" in one of my functions, which takes an array of pointers as argument.

Now, how do I check if an array contains junk values (might be using conditional break point) during run-time? Say, I don't access the pointer and hence the program doesn't break.

What is the condition to be checked for to identify a junk pointer?

هل كانت مفيدة؟

المحلول

You don't test for junk, you put non-junk values in the array at some point between the time you create the array, and the first time you consider using the values. Usually you do it when the array is created:

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

Valgrind uses its own tricks to identify what it thinks is junk, but those tricks are outside the scope of the standard, and regular C code can't use them (or anyway shouldn't try). Even if you could somehow hook into what valgrind does, you'd end up with code that doesn't work on all implementations, or that only works when run under valgrind.

نصائح أخرى

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.

You can't differentiate a valid pointer and junk(uninitialized) pointer, they are all just numbers.

The fact that you are dealing with a "junk" pointer at some point in your code indicates, there's a problem before reaching that point.

You need to systematically initialize all your pointers to NULL. When you deallocate memory reset your pointer to NULL as well. This can be done using "constructor/destructor" functions wrapping malloc/free for instance. Only then you can test for NULL valued pointer to see if something went wrong.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top