Narcolapser
Narcolapser

Reputation: 6221

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?

Upvotes: 2

Views: 141

Answers (4)

Clifford
Clifford

Reputation: 93466

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.

Upvotes: 2

Jens Gustedt
Jens Gustedt

Reputation: 78903

t is a local variable who's lifetime ends with the end of each iteration. So keeping an address of that beyond that iteration is undefined behavior. You have to allocate copies of tree nodes with malloc.

Upvotes: 1

Kevin
Kevin

Reputation: 56049

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.

Upvotes: 4

TJD
TJD

Reputation: 11896

qsort is corrupting memory. If this is a qsort you wrote, it could have an error that writes to an invalid place. If this is a library qsort, it is probably a recursive function that overflows the stack, corrupting your local vars.

Upvotes: 0

Related Questions