alguru
alguru

Reputation: 404

Why does my assignment statement ruin my data?

Take a look at this code:

void insert(Poly **A, int degree, int coef2) {
    heapSize = heapSize+1;
    Poly *key;

    if (heapSize == 1) {        // heap was originally empty
        key->coef = coef2;
        key->degree = degree;
        A[heapSize-1] = key;
        return;
    }

    // create an "minus infinity" degree poly 
    int keyDegree = degree;

    key->coef = coef2;
    key->degree = MIN_INT;

    A[heapSize-1] = key ;
    heapIncreaseKey(A, heapSize-1, keyDegree);
}

Poly is a struct whose members are both of type int. A is an array of Poly pointers. Whenever the statement A[heapSize-1] = key (in the if block) is executed, the members of key change for some reason to "junk" values.

For example, just before that statement is executed, the values of the members of key are 5 and 6. After this statement is executed, the values change to some 8 digit junk numbers.

Why is that?

Upvotes: 0

Views: 254

Answers (6)

aksommerville
aksommerville

Reputation: 358

key doesn't point to anything. Also, the allocated length of 'A' is not provided.

I recommend you brush up on 'malloc', etc.

Upvotes: 0

Genschi
Genschi

Reputation: 134

You have to malloc your pointer before you can use it.

Upvotes: 0

Valery Arkhangorodsky
Valery Arkhangorodsky

Reputation: 163

Allocate memory for key and change a signature to pass in size for the A array. Verify that the heapsize is still within allocated range for A. Even better, you don't need key variable if you refactor to keep structures rather than pointers in your array of Poly's. Then you could just assign your two inputs into the A directly with something like     A[heapSize].coef=coef2; Also you could simplify things a bit by using heapSize in your function without incrementing it in the first line and only increment it at the point of exit. This way you don't need to use heapSize-1 everywhere.

Upvotes: 1

sverre
sverre

Reputation: 6919

You are missing

key = malloc(sizeof(Poly));

Declaring key gives you a pointer, but it doesn't point at a valid location. Dereferencing key causes undefined behaviour.

EDIT

Also, it looks like heapsize is a global constant while A is a pointer to the heap. Having a global variable recording the size of a non-global seems strange.

I would make heapsize a variable with the same scope as A, and pass a pointer to it as an argument to functions dealing with A.

Upvotes: 4

Joshua
Joshua

Reputation: 43317

key is an uninitialized pointer, and you are writing to it.

That way lies strongly undefined behavior.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249404

key is an uninitialized pointer, and then you dereference it and assign values into the nonexistent place it points to. This would have been caught by valgrind.

Upvotes: 2

Related Questions