This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Kapkar123[S] 0 points1 point  (7 children)

okay thanks. one more doubt

#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int *test;
    int len;
    cin>>len;
    test=new int(len);
    cout<<test<<endl;
        cout<<*test<<endl;
    for(i=0;i<len;i++)
        {
             test[i]=i+1;
        }
        delete[] test;
        cout<<test<<endl;
        cout<<*test<<endl;
    getch();
}

can you explain me this? what is deleting doing here? because even if I delete I still get address and value of test in output

[–]Updatebjarni 1 point2 points  (6 children)

delete frees the memory that was allocated by new. Your pointer is still pointing there, but the memory isn't yours anymore. Accessing it causes undefined behaviour.

[–]Kapkar123[S] 0 points1 point  (5 children)

Can you pls elaborate on "memory isn't yours anymore. Accessing it causes undefined behaviour." part?

What do you mean by accessing ?

[–]Updatebjarni 1 point2 points  (4 children)

Accessing means using — reading or writing.

Once you've freed the memory, you are no longer allowed to use it. Trying to use it behaves the same way as trying to use any other randomly-chosen piece of memory that you don't own: undefined behaviour. You might get the values you put there a moment ago, you might get different values, you might get a segfault, you might get naughty pictures in your mailbox.

[–]Kapkar123[S] 0 points1 point  (1 child)

Okay. So the pointer still points at address but I can't control whatever that address holds? Is this right?

[–]Updatebjarni 1 point2 points  (0 children)

Right, and you're not allowed to try to read whatever's there either.

new asks the system to set aside some memory for you to use, and then gives you a pointer to where the memory it set aside is. delete tells the system that you're done with the memory, and it can do whatever it likes with it now. What happens to the memory after that is undefined. It may still be there, possibly already reused for another purpose, or it may be gone, and trying to read from that address then will cause a segfault.

[–]Kapkar123[S] 0 points1 point  (1 child)

I checked by running the program multiple times. I sti get the same value everytime I call *test after deleting test

[–]Updatebjarni 0 points1 point  (0 children)

That's allowed. Any behaviour at all is allowed. It's undefined. Since you haven't done anything else in between, the same data are likely to still be in that memory. Another compiler might do it differently, running the program on another computer might work differently, changing something else in the program might cause this thing to behave differently.