variables vary mysteriously

Question: what is causing these values to change randomly?


Info:

My Code:

int q = nonZero;
for(j = nonZero;j>1;j--)
{
    printf("Top: %i %i\n",j,q);
    qsort(tree,j,sizeof(Node),cmp);
    printf("Bottom: %i %i\n",j,q);
    Node t = {tree[0],tree[1],-1};
    tree[0] = &t;
    tree[1] = tree[j];
    tree[j] = NULL;
}

Not a complicated little program. make a node out of the top two nodes on the tree, make that the new top node, resort the array, repeat. I added 'q' in as a debug value, I'm completely clueless as to what exactly is happening. If I try and have it run, j typically starts at 73, which it should, the expected is that it would then be 72,71,70,69,68...3,2 and that q will remain 73 indefinitely. here's my output though:

Top: 73 73
Bottom: -796584576 32767
Segmentation fault

but thats not all, w/o recompiling, i got:

Top: 73 73
Bottom: 0 0
Segmentation fault

it consistently would give me one of those two outputs. after several runs I saw that 32767 never changed, the q value, but the j value, here -796584576, was always some different absurdly large negative number. anyone have any idea why on earth it would seem as if qsort was changing my j value, as well as what seems to be a completely unrelated value of q?

Answers


The qsort() call suggests that tree[] is an array of Nodes, but the statement tree[0] = &t; rather suggests that it is an array of pointers. That being then case then:

qsort( tree, j, sizeof(&Node), cmp ) ;

or better

qsort( tree, j, sizeof(*tree), cmp ) ;

the latter ensures the size is the sizeof whatever tree is an array of regardless of its type and is therefore safer and more maintainable.

Assigning the address of t to a variable with greater scope than t is also doomed.


I'm not sure if it's your problem, but since t is a local variable, it will go out of scope at the end of that loop, and so assigning it to tree[0] makes tree[0] undefined.


Need Your Help

Definition of operators

c++ class operators

I am trying to define some operators.

Android emulator infinite loading and errors when GPU emulation is enabled

android-emulator gpu emulation

I have downloaded the entire Android SDK from the official website and I installed a new emulator (Android 4.0.3). As long as I don't have GPU emulation enabled it works (even if it need about 5 mi...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.