Hi everyone I was asked to determine why this code while result in a runtime error but I have no idea what I should look at or what to consider? Can anyone help?
what is actually at line 4? Is it a function? Yes I do know about scopes but isn't int calc() a function and can be called in the int main() function? Im sorry I dont really get it
From what I can see, and being a newbee myself is that the calc() function is returning an address which is NOT an interger as suggested by the "int calc()" identifier. Also isnt "int* calc()" a pointer as well and pointing to the calc() function that isnt there?
yes, calc is a function. calc returns an int pointer, that is the * in the function name. All that is OK.
inside calc, when it is called from main, it allocates j, then returns a pointer to j, and when the function exits, j no longer exists.
down in main, ip is a pointer to j, but j was destroyed. The address is not valid anymore.
pointers and the problems they cause take a little while to learn. Once you see it, after going over it a few times, it starts to make sense as to what happens and WHY it happens and if you end up taking an assembly language, you will understand even better WHY the language does it this way.
wish I could go to a school for this to get a better understanding than teaching myself
and not to sound dumb but what happens to &i ? it seems it goes nowhere and its life is over.
The pointer was not destroyed. The memory the pointer accesses is what was lost, and that is because the address is to the variable that was created in the function which is lost when the function is completed. This is what you need to understand.
yes.
you can do this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int * calc()
{
int *ret = newint;
ret[0] = 7;
return ret; //ret gets destroyed. but the MEMORY from the NEW lives on
//and ret is sent back to the caller, so it is saved and usable!
}
...
ip = calc(); //ip is the address allocated by new above.
This works but the function has put the burden of calling the delete function on
the caller. Now main or whatever function called it needs to delete the memory:
..
int * ip2 = ip;
delete ip; //note that what is deleted is the memory from the new statement
//regardless of what variable currently holds it.
//also note that deletion of ip also deletes ip2 as it is the SAME address.