Check If a Pointer Points to Allocated Memory on the Heap

Check if a pointer points to allocated memory on the heap

There's no standard way to do this, but various malloc debugging tools may have a way of doing it. For example, if you use valgrind, you can use VALGRIND_CHECK_MEM_IS_ADDRESSABLE to check this and related things

Checking if a pointer is allocated memory or not

You cannot check, except some implementation specific hacks.

Pointers have no information with them other than where they point. The best you can do is say "I know how this particular compiler version allocates memory, so I'll dereference memory, move the pointer back 4 bytes, check the size, makes sure it matches..." and so on. You cannot do it in a standard fashion, since memory allocation is implementation defined. Not to mention they might have not dynamically allocated it at all.

You just have to assume your client knows how to program in C. The only un-solution I can think of would be to allocate the memory yourself and return it, but that's hardly a small change. (It's a larger design change.)

How to know if a pointer points to the heap or the stack?

There is no way of doing this - and if you need to do it, there is something wrong with your design. There is a discussion of why you can't do this in More Effective C++.

How to know pointer is pointing to dynamically or static allocated memory

You can't know this. This is by definition of your function. Prefer using smart pointers or you have to make pretty clear in your functions documentation that it takes over the ownership of your passed object or array.

C how to check if a memory address is still in scope

EDIT:
You could also skip the structure part and just set the pointer to NULL with macros and then check if it's NULL with a macro;

void some_function(int* input)
{
if (CHECK_POINTER(input))
{
*input = 50;
}

};

int main()
{

int* point ;
CLEAR_POINTER(point);
int a=-1;


some_function(point);
printf("%d\n", a);

ASSIGN_POINTER(point, &a);
some_function(point);
printf("%d\n", a);

}

OLD:
If you are trying to keep track if the pointer is assigned to a certain variable, you could use a structure that contains the pointer variable itself and a variable that is either 0 or 1 when the pointer has been assigned to certain variable.

You can then use macros to assign pointer, clear pointer or check if pointer is assigned a variable address;

#include <stdio.h>

#define DEFINE_POINTER_DATA_STRUCTURE(data_type)\
typedef struct \
{ \
int is_assigned; \
data_type *pointer; \
}PDS_##data_type;

#define POINTER_DATA_STRUCTURE(data_type) PDS_##data_type

// The above allows you to have custom types

DEFINE_POINTER_DATA_STRUCTURE(int) // Define a struct of int pointer

#define ASSIGN_POINTER(structure, address) structure.pointer = address; structure.is_assigned = 1;

#define CLEAR_POINTER(structure) structure.pointer = 0x00; structure.is_assigned = 0;

#define CHECK_POINTER(structure) structure.is_assigned

#define GET_POINTER(structure) structure.pointer

void some_function(POINTER_DATA_STRUCTURE(int) input)
{
if (CHECK_POINTER(input))
{
*GET_POINTER(input) = 50;
}

};

int main()
{

POINTER_DATA_STRUCTURE(int) pointer_structure;
CLEAR_POINTER(pointer_structure);
int a=-1;


some_function(pointer_structure);
printf("%d\n", a);

ASSIGN_POINTER(pointer_structure, &a);
some_function(pointer_structure);
printf("%d\n", a);

}

How can I tell whether a pointer points to the stack or to the heap?

You can't realistically hope to distinguish between stack and heap memory in this way. You say "the stack", but there are many. One per thread. You'd need to check the reserved addresses of all the stacks. And how will you find a list of all the stacks to do that checking without encountering a terrible race condition?

It is folly to try to get a record to behave differently depending on whether it is allocated automatically on the stack, or dynamically on the heap. Those behaviour variations need to be handled by the consumer of the record.

A scenario to make you re-consider is that where your record is contained inside another type (record or class). The instance of the containing type may be heap allocated but you must not free the contained record, even though it resides on the heap.

The bottom line of heap allocation is that you need to remember when you allocated off the heap and ensure that you free anything allocated on the heap. If you forget who owns the memory by a pointer you are doing it wrong.

Don't continue down the dead end trail that you have started along.

How to determine if returned pointer is on the stack or heap

Distinguishing between malloc/free and new/delete is generally not possible, at least not in a reliable and/or portable way. Even more so as new simply wrapps malloc anyway in many implementations.

None of the following alternatives to distinguish heap/stack have been tested, but they should all work.

Linux:

  1. Solution proposed by Luca Tettananti, parse /proc/self/maps to get the address range of the stack.
  2. As the first thing at startup, clone your process, this implies supplying a stack. Since you supply it, you automatically know where it is.
  3. Call GCC's __builtin_frame_address function with increasing level parameter until it returns 0. You then know the depth. Now call __builtin_frame_address again with the maximum level, and once with a level of 0. Anything that lives on the stack must necessarily be between these two addresses.
  4. sbrk(0) as the first thing at startup, and remember the value. Whenever you want to know if something is on the heap, sbrk(0) again -- something that's on the heap must be between the two values. Note that this will not work reliably with allocators that use memory mapping for large allocations.

Knowing the location and size of the stack (alternatives 1 and 2), it's trivial to find out if an address is within that range. If it's not, is necessarily "heap" (unless someone tries to be super smart-ass and gives you a pointer to a static global, or a function pointer, or such...).

Windows:

  1. Use CaptureStackBackTrace, anything living on the stack must be between the returned pointer array's first and last element.
  2. Use GCC-MinGW (and __builtin_frame_address, which should just work) as above.
  3. Use GetProcessHeaps and HeapWalk to check every allocated block for a match. If none match for none of the heaps, it's consequently allocated on the stack (... or a memory mapping, if someone tries to be super-smart with you).
  4. Use HeapReAlloc with HEAP_REALLOC_IN_PLACE_ONLY and with exactly the same size. If this fails, the memory block starting at the given address is not allocated on the heap. If it "succeeds", it is a no-op.
  5. Use GetCurrentThreadStackLimits (Windows 8 / 2012 only)
  6. Call NtCurrentTeb() (or read fs:[18h]) and use the fields StackBase and StackLimit of the returned TEB.

Check if memory is on the Heap?

While there are system specific approaches which will probably be able to tell whether memory is from heap or from a stack, that actually doesn't really help: you may have got a pointer to a member of another object on the heap. The memory would be on the heap but you are still not responsible for deleting the object. Put differently: do not go down the path you are on!

The proper way to deal with the problem is to make the ownership semantics blatantly clear in the interface and go with that. There are essentially two directions you can take:

  1. Your class can deliberately not take over responsibility for the pointer passed in the constructor! Instead, it is the responsibility of the user of your class to deal with these objects and to guarantee that they are valid while your objects exists. If you can get pointers to stack (or member) objects the user already has to guarantee the validity of these objects anyway and for other ways it may be entirely trivial for the user to deal with them, e.g., by managing them via a std::unique_ptr<OtherClass>.
  2. Your class takes responsibility of all objects passed and it will delete all of them. It becomes the responsibility of the caller to not pass pointers to objects managed elsewhere, e.g., to objects on the stack or member objects.

There is sort of a hybrid approach where your class takes responsibility of objects some times but not always. However, the implementations of such an approach is really a combination of the two approaches above: you'd take a suitable smart pointer as constructor argument and it is the user's responsibility to make sure that the smart pointer is constructed appropriately by the user of your class. For example, your class could take a std::shared_ptr<OtherClass> for which the normal construction will delete the object. When the user wants to pass in a pointer to an otherwise owned object the std::shared_ptr<OtherClass> would be constructed with a deleter which does not delete the pointer. Here is a simple program demonstrating the two different management strategies for std::shared_ptr:

#include <iostream>
#include <memory>

struct foo {
char const* name;
foo(char const* name)
: name(name) {
std::cout << "foo::foo(" << name << "): " << this << "\n";
}
~foo() {
std::cout << "foo::~foo(" << name << "): " << this << "\n";
}
};

int main() {
std::shared_ptr<foo>(new foo("heap"));
foo f("stack");
std::shared_ptr<foo>(&f, [](auto){});
}

How can i check if char pointer is points nothing after allocated

You need to modify the check to check against the returned pointer, not the content. Something like

if( p == NULL) {
fprintf(stderr, "The pointer points nothing !\n");
return 1;
}

should do. Quoting the standard regarding the return values:

The malloc function returns either a null pointer or a pointer to the allocated space.

The null pointer is returned in case of a failure, otherwise the pointer returned should be non-equal to a null pointer.

That said,

  • The initial content of the pointed memory is indeterminate, do not attempt to verify it. Quoting from the standard,

    The malloc function allocates space for an object whose size is specified by size and
    whose value is indeterminate.

    That goes for your other question regarding "checking the length" of the pointer - it's pointless. Unless you have stored (write) some value into it - there's no point trying to measure the initial content, as it is indeterminate. You may eventually run into undefined behavior.

  • The cast for the returned pointer by malloc() and family is superfluous. It can be totally avoided in C.

  • sizeof(char) is guaranteed to be 1, in C. Thus, using sizeof(char) as a multiplier, is again not needed, per se.



Related Topics



Leave a reply



Submit