1
char* pArray = nullptr;
{
    char buffer[64];
    sprintf_s(buffer,"Time: 123456");
    pArray = buffer;

}
cout<<pArray<<endl;

"Time: 123456" is displayed even though the buffer has been deallocated back to the stack. What is going on here? Is this safe? Not safe?

2
  • No, it is not safe. Its undefined behavior. Commented Apr 15, 2012 at 18:42
  • There are maybe another 20 or 30 posts here on SO asking the same question... Commented Apr 15, 2012 at 18:52

2 Answers 2

2

It's undefined behavior. The memory probably isn't cleared.

It's pure luck your print statement works. When an object goes out of scope or is deleted, the memory is marked as released and not actually erased. The program can reclaim it and overwrite it.

Sign up to request clarification or add additional context in comments.

Comments

0

You are not using the memory anymore, but the data is still there.

You should not do stuff like that unless you know what you're doing.

You can use a hack like that to pass some parameters to a function but it's very unsafe.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.