Question

After a huge amount of digging and searching I found the root of my problem. In essence this code is executed and, in its own project it causes the same error. I see that I cannot reset a smart pointer to a new string...but why? Also is there a simple way around this?

scoped_array<char> sptr;
char* nptr = "Hello";

sptr.reset("");
sptr.reset(nptr);

EDIT -

I think I've figured it out. While resetting, the smart pointer tries to delete and empty character array ("") which, because the new operator was not used, was not allocated on the heap (ahem !!?!!?!???!?!). Therefore this program will break miserably when it tries to deallocate the memory. So correct me if I'm wrong but would the string itself be stored in the program's executable byte stream itself? If so, just for future reference, is there a way to force the allocation of a new string?

Was it helpful?

Solution

You're correct in identifying the error. scoped_array will call delete[] on the object it's holding; that is, after all, the sole purpose of its existence. You can't delete[] something that wasn't new[]'d, or you get undefined behavior.

However, you should just use std::string if you want a dynamic string. Anything you try to create to allow scoped_array<char> to act like a string is just going to end up as a shoddy version of std::string. Then it's as simple as: std::string s; s = ""; s = "Hello".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top