...

View Full Version : Pointer Question



spadez
05-10-2009, 06:48 PM
Hi,

Ive been given this code:


int i=0, j=0, *k=0, *l=0;
k = l;
l = &i;
j = *k;

Ive also been told that this code crashes. The question is, explain the cause of the crash, and correct the program by rearranging the istructions without modifiying them.

Can someone help me to understand why it is crashing. Ive been told that line 4 is the problem, and that reversing line 2 and three fixes the problem.

Ive even been told it has something to do with dereferencing, but for the life of me I cant find any information or tutorials online that will help me understand what is going on.

Can anyone explain this to me?

oracleguy
05-10-2009, 08:48 PM
You are correct that line 4 is the issue. What is happening there is that k is pointing to memory address zero. So this line j = *k says assign the data at the memory address stored in k to the variable j.

And memory address zero is considered null in the C and C++ and you cannot de-reference a pointer at that address. So think about how re-arranging the instructions could prevent this problem and where k is not null.

Reversing the two lines like you are thinking will solve the problem. Is it clearer why doing so fixes the problem?

spadez
05-10-2009, 09:45 PM
Im still not 100% on this though. I think its the second line that is confusing, is it setting the value of the pointer k equal to the value of the pointer l? In which case setting k equal to 0.

Is it correct to say that k isnt then updated in line three, becuase the value of l is changed after k has been equated to the value of l. For example:

l = 3
k = l;
l = 5;

Would the value of k be 3 and not 5?

oracleguy
05-10-2009, 11:13 PM
Im still not 100% on this though. I think its the second line that is confusing, is it setting the value of the pointer k equal to the value of the pointer l? In which case setting k equal to 0.

Is it correct to say that k isnt then updated in line three, becuase the value of l is changed after k has been equated to the value of l. For example:

l = 3
k = l;
l = 5;

Would the value of k be 3 and not 5?

Correct, k would be equal to 3.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum