Nate
Nate

Reputation: 17

Is it possible to assert that a pointer is pointing to an array?

I am creating a deconstructor, and I want to assert that my pointer float *queue is pointing to an array of floats. The compiler does not seem to like

assert([]queue);

and my program seg faults if I use

assert(queue != NULL); delete []queue;

. Thanks for the help.

Upvotes: 0

Views: 187

Answers (1)

walnut
walnut

Reputation: 22152

No you cannot.

You can test whether a pointer has a null pointer value by comparing it against nullptr (or NULL in pre-C++11; NULL should never be used since C++11), but you can never tell whether a non-null pointer is pointing to a valid object, whether that object is part of an array or whether that object/array was allocated by new/new[].

It is the programmer's job to assure that the code can never reach a state where the above information is needed, but unavailable.

The easiest way of doing that is to never use raw new/delete. Instead only use std::vector and std::unique_ptr.


You also don't need to check for a null pointer before calling delete[]. delete[] can be called with a null pointer, in which case it simply doesn't do anything. You cannot call delete[] with a non-null pointer that doesn't have a value returned by new[] (and that hasn't been delete[]ed yet) tough. That would have undefined behavior.

Upvotes: 2

Related Questions