Way to detect if pointer points to a..., exactly where?

char* cc = "Something string like";
char* ccn = new char[2];
ccn[0] = 'a';
ccn[1] = '\0';
cout << cc;

The second pointer, in order to prevent mem leak, should be delete[]'d but how can one detect if pointer actually points to new'd mem or not (like the one in first line)? And where is the first string created?

Upvotes: 0

Views: 106

Answers (2)

Steve Jessop
Steve Jessop

Reputation: 279395

In standard C++, there is no way to know from a raw pointer alone, how the associated resources (if any) were allocated.

You could perhaps use smart pointers instead, since they pass resource ownership information along with the raw pointer value. For example:

template <typename T>
struct noop_deleter {
    void operator()(T *p) {}
};

boost::shared_array<const char> cc("Something string like", noop_deleter<char>());
boost::shared_array<char> ccn(new char[2]);

ccn[0] = 'a';
ccn[1] = 0;
cout << cc.get();

Upvotes: 0

user2100815
user2100815

Reputation:

No, you can't, and you shouldn't design your applications in a way that expects you to be able to do so. Re your question about where the first string is created - the answer is "somewhere convenient for your compiler" - it is not specified by the C++ standard.

The obvious way round this problem is not to use arrays of char, but to use std::strings.

Upvotes: 8

Related Questions