Miket25 Miket25 - 11 months ago 42
C Question

Is it possible to determine who owns a segment of dynamic memory during runtime?

Suppose I allocate a piece of dynamic memory, and it was successful. Later on, there is a possibility that this piece of memory no longer belongs to the user. Is it possible to determine if the user still owns this piece of dynamic memory? i.e.

#include <stdio.h>
#include <stdlib.h>

int main(){
int* ptr = malloc(sizeof(int));

/* ... ptr may have been freed ... */

belongToUser(ptr); /* <- some sort of check? */

Answer Source

There is a (neither clean nor safe) possibility to check:

  1. Register a signal handler for SIGSEGV
  2. Access the memory
  3. Return not mapped if the signal handler was run, mapped otherwise

As mentioned, I'd never recommend to check, but to write C programs that remember (pointer = NULL).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download