How to check if a pointer variable is junk during runtime? - c

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?

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 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.

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.

Related

C - Newly declared array contaminated with values from other variables

I'm alarmed to see that a newly declared array is being contiminated with some random values and some partial values from other variables within my C program.
Here's the source code of my function. I'm basically writing some pseudo code in preparation for doing some complex XML parsing and file manipulation (think similar to a mail merge). Anyway I'm concerned if there are random values in my newly declared array. Why isn't it empty of values when I first declare it?
Do I really need to traverse my entire array to set it's elements to blank values before I begin assigning values or is it likely that there's something wrong with other variable declarations in my code?
Thank you for your help.
Regards,
Chris
void ShowArray(void)
{
char aryString[5][5][255];
sprintf(aryString[1][1],"AAAAA");
sprintf(aryString[1][2],"BBBBB");
sprintf(aryString[1][3],"CCCCC");
sprintf(aryString[1][4],"DDDDD");
sprintf(aryString[1][5],"EEEEE");
sprintf(aryString[2][1],"A2");
sprintf(aryString[2][2],"B2");
int numRow;
int numCol;
for (numRow=1;numRow < 6;numRow++)
{
for (numCol=1;numCol < 6;numCol++)
printf("%d,%d:%s\n", numRow, numCol,aryString[numRow][numCol]);
}
}
Unfortunately you have to initialise the values of every element in an array.
Having random values populating your array and variables when you first declare it is normal. This is because when your computer frees up memory, it doesn't reset them to zero. You computer just allows other programs to overwrite the values in those newly freed memory locations.
Those uninitiallized values are just leftovers from other functions.
A local variable in a function will have an initially undefined value. This is, in fact, what you want, since the alternative would be for the compiler to force an initialization that in most case you don't want, unavoidably slowing your function. It is your responsibility to ensure that any variable has been properly defined before trying to use its value. I have never found this to be a problem.
You are also writing to the [1][5]th string in your code with sprintf. Your aryString variable is of dimensions [5][5][255]. Remember that array indexing in C is 0-based. You should not go beyond the [1][4]th element. You might want to delete that line and try again, because you will end up corrupting your own data by yourself.
Yes, all auto(opposite to static, which is declared explicitly) variables you declare in a function calls for manual initialization. The compiler won't initialize it automatically because it don't know what do you want to be written to that memory. To make it write the default value, which is usually 00000000, to uninitialized variables, write char aryString[5][5][255] = {};, or more commonly, char aryString[5][5][255] = {0};.
Also, the value an uninitialized variable contains is not only a garbage value, but also likely a trap representation, and merely accessing it will cause undefined behavior.

segmentation fault core dump after program runs and displays output

I have made some changes to my program that I started with: But for another reason I am getting a segmentation error. It happens after my output and I think it may have to do with my free statement in the destroy function. I ran it through gdb and it told me I was trying to access a 0X000000d memory location which is weird because I can print out the memory location of my struct and it shows something different. I know I have probably missed something very small. any help would be greatly appreciated thanks!
had to take m code down since it is an on going project in school thanks for the replies I will post it back on once we have a grade.
You have undefined behavior in your code.
Take this line:
struct Person *UserOne=inputvalues(UserOne);
Here you define a variable UserOne and initialize it by calling the inputvalues function, for which you pass the uninitialized pointer. That means inside the inputvalues function, the temp pointer is uninitialized, and its value is indeterminate leading to said UB when you dereference the pointer.
One possible solution is to define a structure variable that is not a pointer, and use it when calling inputvalues, or by dynamically allocating a structure and pass to the function. Or to redesign the program to not pass an argument to the function at all, and let the function itself allocate the structure.
Using uninitialized variables like this is easily detectable by compilers, and most can issue warnings for it. If you don't get such a warning you might want to consider enabling more warnings.

How to check out the values of dynamic allocated memory in debugging mode?

i'm using eclipse and netbeans for c, and i'd like to check out the values of variables that are dynamically allocated in the memory when i'm debugging (both in eclipse and netbeans).
for some reason, i can only see the value of the pointer itself, and it's first item.
to illustrate: with this code:
int foo[10];
i can check the value of the entire array later on (when debugging).
for example, i can check out the value of foo[7] in the watches window.
but with this code:
int *bar = malloc(10*sizeof(int));
i can only check out where bar is pointing, and the value of bar[0] (but not the other values).
how can i watch all the values of the array?
UPDATE: the issue was solved in both eclipse and netbeans.
in eclipse: right click the desired variable in the Variables window -> select Display As Array -> fill in the start index and the array length.
in netbeans: in the Watches window add a new watch with the following format:
*((bar)+0)#10
where bar should be the pointer name,
0 should be your start index
and 10 should be its length
if i may add something personal: this is my first ever message on stackoverflow. i hope you found it useful.
As you are on a pointer variable, the only knowledge that the debugging tool can infer automatically is that you have an address on an integer value. After that fact you can have theoretically anything behind your integer value, it is not possible for the tool to guess that the pointer is in fact the first element of an integer array.
That said, you can try to add a custom watch expression (at least on Eclipse, i don't know netbeans) which casts your pointer into the integer array. I don't know if you can cast with a precise array length.
Something like (int[])bar will certainly work but maybe this form may work either (int[10])bar.
Another solution is looking directly on the memory view at the pointer address, but it is more of a mental sport to convert raw endianness hexadecimal output to integer values...
Now if your pointer is always allocated to a memory block of 10 integers, you should preferably consider to statically allocate it using the array form int bar[10];
I don't know if it will work in Eclipse or Netbeans, but you could try adding a watch on *(bar + 1) for the second "entry". However you probably can't use bar as an array unless the debugger allows you to typecast it to an array (like (int[])bar, which I have no idea if it will even work in real C).

How to know whether an array is initialized in C

How to know whether an array is initialized in C ? Functions like strlen() are not helping me as I dont want to know whether the array is empty or not.
There's no way to test that at runtime -- an uninitialized array looks just like one that has been initialized with garbage.
Depending on what you're doing, you need either to make sure the array is actually initialized or explicitly pass around a flag that tells you whether the values in the array are meaningful yet.
Also note that "whether the array is empty" is not a very meaningful concept in C. The array is just there, and it always contains whatever number of bits are necessary to represent the elements it's declared to have. Those bits may not have meaningful values, but the're always there.
You can't by using programmatic language features.
But you can by design and discipline. At declaration time set your array as a pointer to NULL.
Then make a function to assign both memory and value to your pointer and a corresponding freeing function to destroy it when is not needed anymore, setting it to NULL again. And then making every function that processes check for NULL as an error condition.
To do bounds recognition, set the last element to NULL.
Example:
char* myArray=NULL;
/* other code */
myArray = createMyArray(n_elements);
memset(myArray,0,sizeof(int)*n_elements); /* Set the allocated memory to zero */
/* other code */
myArray[0]=functionReturningAString();
myArray[n_elements-1]=functionReturningAnotherString();
/* other code */
/*Processing*/
char* incr=myArray;
while( incr != NULL){
processArray(incr);
incr++;/* Increments by size of char pointer to the next pointer*/
}
free_Array(&myArray);/* this function calls free() and sets myArray to NULL*/
This is usable, when you need a lot of efficiency. Otherwise you should either create your own arraylist or use an existing library which provides it.
You need too much discipline to keep track of every possible error condition, so it can be tiresome.
Usually is just better to just use a library which provides arraylist, linkedlist, HashSets, etc. For C I use a lot of Glib functions for this.

C variable being set to 0 after passing to function

So I am running into an odd problem. I have a pointer to a struct, and I am passing it to a function. Once inside that function, one of the variables I am interested in appears to be 0, but before passing the struct to the function I check to make sure that specific variable is not 0. The weird thing is this does not happen every time, only once in a while. Has anyone ever seen something like this happen before?
Source Code:
if( expand->num == 0)
return status;
status = decode( expand );
...
Status_type decode ( expand_type * expand )
{
if(expand->cur_num >= expand->num) // Here is where my error occurs
// 'num' is 0.
{
// Do stuff
}
}
Sounds like a "dangling pointer" problem: You have a rogue pointer that is pointing to memory which does not belong to it (e.g., not an allocated instance of the type the pointer references), and somewhere the program instructs the pointer to use that "value", and the pointer is now overwriting that value (which is accidentally on the value you are inspecting).
Your symptoms match: Intermittent, memory overwrite when it appears there should be no memory overwrite.
Those can be very painful to track down, because you need to check the integrity of all your pointer operations, even the ones that have nothing to do with the code you are currently looking at (monitoring).
One thing to help you track it down would be to explicitly initialize all pointers to "null" on instantiation. This is generally not necessary, but can be helpful for debugging, because indirection-on-null will typically crash your program right there (which is what you want), rather than remain as a "hidden problem" as you access memory that is not yours (because pointers in C are by default not initialized to null). So, for example:
int* p; // Initialized to "garbage" memory address
...change to:
int* p = NULL; // Force initialization for debugging, crashes on indirection
On the bright side, when you suffer that enough, you have habits that make you very careful with your pointers. ;-)))
Three possibilities come to mind.
Corruption from another task.
Uninitialized pointer
Dangling pointer
Of these three possibilities, my money (based on the current information) is that of the uninitialized pointer.
My guess is that the value the uninitialized pointer has points just far enough down the stack that when decode() is called, the memory where 'expand->num' is stored is corrupted by either copying the parameter 'expand' onto the stack, or copying the return address to the stack, or by setting up the stack frame for decode().
Finally found the problem. There are multiple threads, and two threads were trying to access the same variable at the same time (the expand variable), causing it to be overwritten! So I had to stop one of the threads at a certain point so both wouldn't be accessing the same stuff.

Resources