0

The question is pretty much that. In C++, if a pointer is not NULL is there any way to determine if the data pointed was allocated on the heap (new-type allocation) or on the stack (typical allocation and current scope lifetime).

I have an implementation of smart pointers and arrays (I know smart pointers exist in C++11 but I avoid them until there's a cleaner way to add smart arrays than currently) in which I keep track of reference count and so on. Whenever a pointer is not referenced at all anymore it is delete. Problem is, the current implementation doesn't prevent to give to the class a pointer to a variable on the stack (I do not want to force the creation of the pointer by the smart pointer, I have specific case where I want to do the allocation myself, for example when creating an array in a function and in the same function it needs a resize before being handed to the caller and so on), but if I give such a pointer, the class will try to call a delete or a delete[] on this pointer, which will result in undefined behavior (well let's be honest, a crash in most cases).

So is there a way that I check if I should or not delete this pointer on destruction or if the class should even accept it in the first place ?

Thanks in advance everyone.

Jeremy B.
  • 73
  • 9
  • No general/portable solution for detecting this. I did not get why you're not using standard smart pointers... – quantdev Jul 29 '14 at 14:00
  • Well standard C++11 smart pointers do not have a direct array equivalent, you need to provide a customized deleter (don't remember how to do this since the solution was not too elegant). Since the algorithm is very basic and far from CPU intensive I stick with my implementation for now ;) Thanks for the info by the way ! – Jeremy B. Jul 29 '14 at 14:07
  • @DevilBlackDeath C++11 has `std::array` and `std::vector` depending on whether you need stack or heap allocation. – Mark B Jul 29 '14 at 14:14
  • @MarkB But std::vector doesn't allow me to manage the lifetime of the allocation the same way a smart array does, which is why I use both ;) For a heap allocation that needs to be freed when exiting the current scope I use a std::vector but for a more granular lifetime I will use smart arrays (that's the case when I manage my SFML textures for example ;) ) – Jeremy B. Jul 29 '14 at 14:20

1 Answers1

1

No.

The best you could hope for is a non-portable hack based on some particular library's implementation details, and even that would have a non-zero false-positive results.

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • Well too bad :( At least this produces a rather understandable error at run-time when you're familiar with pointers, and since I don't intend to let anyone unfamiliar with C++ touch my code my current implementation should do the trick :) – Jeremy B. Jul 29 '14 at 14:08