views:

351

answers:

5

How does one differentiate between pointers and references at runtime? For example, if I wanted to free a pointer of a data type without knowing whether it were a pointer or not how would I do so? Is there any method to tell if a variable has been allocated on the stack or through malloc()?

void destInt(int* var)
{
   free(var);
}


int num = 3;
int &numRef = num;
int* numPtr = (int*)malloc(sizeof(int));
*numPtr = num;

destInt(&numRef); //Syntactically correct but generates invalid pointer()
destInt(numPtr); //Fine syntactically and logically
+7  A: 

No, not in the general case and not in a portable manner. If you know where in memory the heap is, you can make an educated guess, but not in any reliable way.

EDIT: also note that C does not have references. The &-operator in C is used to take the address of a variable.

JesperE
+4  A: 

If it's ANSI C, then there's no such thing as a reference, so you might want to rephrase your question to talk about pointers to heap allocated or pointers to stack allocated objects.

Often the address of the heap is 'small' and grows up, and the stack is 'big' and grows down, but that's only a heuristic and non-portable.

Pete Kirkham
A: 

When using malloc, Memory is NOT allocated in the STACK, but in the heap.

Alphaneo
+1  A: 

In C++, the information differentiating whether it is a reference or a pointer is part of the type information at compile-time. In C, this is an irrelevant distinction in semantics.

If you need to use & to get the address of something, then you cannot delete or free it. Otherwise, if you're passing a pointer around, you need to document which functions have the authority to delete or free it. The easiest way to do this in C++ is to use a smart pointer class like a shared_ptr or scoped_ptr.

greyfade
+1  A: 

Whatever you're trying to accomplish.... don't do it this way.

You can usually obtain the bounds of the stack, but this would normally be a pretty compiler/platform specific process. Same with the heap. If you've hooked new and delete with your own versions you probably know where the heap starts and ends. Otherwise you don't.

However, the tree you're barking up is not a good one. If you're convinced you really need to do it this way, pass the information around with the pointer. Wrap it in a struct that also has a bool called needsFree or something. But otherwise, the fact that you're running into this problem often indicates that the problem you're trying to solve could be solved in a cleaner way.

Dan Olson