c free() function question [duplicate] - c

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C programming : How does free know how much to free?
Hi,
when i have following code:
void *ptr = malloc(100); // alloc 100 bytes
// do sth
free(ptr);
how does the free() function know how much space has to be freed?
thank you!
--
ok i have found other questions asking the same, please close - sorry

This information is usually contained in some memory area managed by the malloc implementation. The information often preceeds the actual memory handed out to you by malloc, but that's an implementation detail, and you cannot rely on anything here.

It's implementation dependent but usually the underlying system mas a map of addresses to blocks and it knows the size from that memory map.
Here is the striped down code from glibc which shows it doing basically what what I just said.
void fREe(Void_t* mem)
{
arena *ar_ptr;
mchunkptr p;
if (__free_hook != NULL) {
(*__free_hook)(mem, NULL);
}
if (mem == 0) /* free(0) has no effect */
return;
p = mem2chunk(mem);
if (chunk_is_mmapped(p)) /* release mmapped memory. */
{
munmap_chunk(p);
return;
}
ar_ptr = arena_for_ptr(p);
chunk_free(ar_ptr, p);
(void)mutex_unlock(&ar_ptr->mutex);
}

Related

Allocating memory through calloc in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am simply testing what would be the output if I try to dereference a pointer, which points to out of range of dynamically created memory using calloc() and expecting memory fault or some garbage value instead. It is giving 0 as output, which is basic feature of calloc() that it intializes allocated memory with '0', or is it just due to undefined behavior?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = NULL;
p = (int *)calloc(10, 8);
if(p != NULL)
{
printf("\n successfully allocated memory ");
}
else
EXIT_FAILURE;
printf("\n Thirty first element of memory is %d \n",p[30]);
}
Result :
successfully allocated memory
Thirty first element of memory is 0
You are trying to access p + 30 * sizeof(int) which is p + 120 while you have allocated only 8 * 10 = 80 bytes, so max address you can access is p[19]
From a language perspective, accessing out of bounds memory is undefined behavior, meaning that anything can happen.
One possible explanation for that particular behavior is that most operating systems will zero out any memory before they give it to your process, independently of what function you where using internally (this is a security measure, so you can't read data that was used by other processes).
To get garbage data, you usually have to have used and freed the same memory before inside your program (in which case it retains its old value). Or of course, if your index is so far off that you are indexing into a neighboring data structure.
The reason your program didn't just crash is that malloc (and similar functions) usually request much more memory from the os, than what you are requiring and use the surplus memory the next time you call malloc. So from the OS perspective you are accessing valid memory, and there is no reason to terminate your program.
Accessing out of range memory is Undefined Behaviour. Hence the value which you get can be 0 or 1 or Batman
The point is, you cannot ask any explanation or reason for things that are undefined. Anything can happen in such a scenario.
Also, you would get a seg fault if you try to access a memory location which your program is not allowed to access. That may not be the case always when you access out of bounds memory. It can lie well inside the user memory area of the program.
I think windows zeroes a freed page before making available for allocation. Have fun with the code below.
#include<stdio.h>
#include<stdlib.h>
#include <windows.h>
#include <signal.h>
int g = 0;
unsigned long long* p=NULL;
void signal_handler(int ssc)
{
printf("Error %d \n", ssc);
printf("segfault after %llu bytes",g*8);
printf("should i go backwards? press enter");
getch();
g=0;
do
{
printf("Virtual Adress:%llu is %llu\n",p+g,*(p+g) );
Sleep(1);
g--;
}
while(1);
}
int main ()
{
if(SIG_ERR == signal(SIGSEGV, signal_handler) ) {printf("error seting signal handler %d\n",SIGSEGV);}
p = (unsigned long long*)calloc(10,8);
if( p!= NULL)
{
printf("successfully allocated memory\n");
}
else
{
EXIT_FAILURE;
}
do
{
printf("Virtual Adress:%llu is %llu\n",p+g,*(p+g) );
Sleep(2);
g++;
}
while(1);
return 0;
}

Issue with PHP pop( ) function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So I'm having an issue with my pop() function, when running my program, the first time I call the pop() function it returns the item no problem, but when it tries to pop the second item in succession, it fails. I can't seem to figure out why, is there something I'm missing in my function?
#define DEFAULT_CAPACITY 16
struct stack {
size_t capacity;
size_t size;
stack_item *data;
};
stack *new_stack (void) {
stack *this = malloc (sizeof (stack));
assert (this != NULL);
this->capacity = DEFAULT_CAPACITY;
this->size = 0;
this->data = calloc (this->capacity, sizeof (stack_item));
assert (this->data != NULL);
return this;
}
void free_stack (stack *this) {
assert (empty_stack (this));
free (this->data);
free (this);
}
static bool full_stack (stack *this) {
return this->size == this->capacity;
}
static void realloc_stack (stack *this) {
size_t old_capacity = this->capacity;
this->capacity *= 2;
this->data = realloc (this->data, this->capacity);
memset (this->data + old_capacity, 0, old_capacity);
assert (this->data != NULL);
}
void push_stack (stack *this, stack_item item) {
if (full_stack (this)) realloc_stack (this);
//increase size of stack
this->data[this->size] = item;
this->size++;
}
stack_item pop_stack (stack *this) {
assert (! empty_stack (this));
printf("Stack size: %lu\n", this->size);
return this->data[this->size--];
}
Depends on what you mean by "fail".
There are numerous reasons it could fail, such as (by no means exhaustive):
code for pushing data is incorrect.
you haven't created a big enough capacity.
you haven't pushed enough items to pop (stack underflow).
The first thing you should do is create a dump_stack function for debugging, along the lines of:
void dump_stack (char *desc, stack *this) {
printf ("%s: size/capacity: %lu/%lu\n",
desc, this->size, this->capacity);
for (size_t idx = 0; idx < this->size; idx++) {
// print out this->data[idx], depends on data type
}
}
This will greatly assist in figuring out where your problem lies, if you call it after each stack operation (push, pop, peek, clear, dup, rot, 2dup, 3rot, and so on).
Now that you've added some more code, there's a few things you need to look at.
First, your stack_item type. Unless this is exactly the same size as char, your memory allocation functions are incorrect. For example, if it's a four-byte integer, you will need to allocate four times as much memory as you currently are. This can be fixed by multiplying the allocations by sizeof(stack_item).
You've done this with the initial calloc call (because you have to provide a size for that) but not in the subsequent realloc ones.
Second, in your realloc_stack function, you really should assert before doing the memset. If, for some reason, the reallocation fails, it's not a good idea to do anything to the memory.
Third, relying on assert to catch errors that may or may not happen at runtime is a bad idea. That's because assert typically does nothing in non-debug code (based on NDEBUG) so, if you run out of memory, you're not going to catch that. You probably need to provide your own error handling stuff in conjunction with exit() (for example).
I'm also not really a big fan of library-type code pulling the rug out from underneath you if it has a problem - I always prefer to have it return an indication to the caller and let that decide what to do (that's why I'll never use GMP in production code since it does exactly that when it runs out of memory).
Fourth, using calloc and memset here is almost certainly a waste since your code knows where the stack end is based on size. Whether those entries above size but below capacity are set to 0 or some arbitrary value is irrelevant since you'll never use them without first setting them to something (with a push operation).

Finding the memory allocated in program? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I get the size of an array from a pointer in C?
How can I get the size of a memory block allocated using malloc()?
void func( int *p)
{
// Add code to print MEMORY SIZE which is pointed by pointer p.
}
int main()
{
int *p = (int *) malloc(10 * sizeof(int));
func(p);
}
How can we find MEMORY SIZE from memory pointer P in func() ?
You cannot do this in a portable manner in C. It may not be stored anywhere; malloc() could reserve a region much larger than you asked for, and isn't guaranteed to store any information about how much your requested.
You either need to use a standard size, such as malloc(ARRAY_LEN * sizeof(int)) or malloc(sizeof mystruct), or you need to pass the information around with the pointer:
struct integers {
size_t count;
int *p;
};
void fun(integers ints) {
// use ints.count to find out how many items we have
}
int main() {
struct integers ints;
ints.count = 10;
ints.p = malloc(ints.count * sizeof(int));
fun(ints);
}
There is no inbuilt logic to find the memory allocated for a pointer.
you have to implement your own method for doing it as brian mentioned in his answer.
And yes,you can find the memory leaked using some tools like valgrind on linux.
and on solaris there is a library libumem.so which has a function called findleaks which will tell you how much memory is leaked while the process is in running state.

Redefining free memory function in C

I'm redefining memory functions in C and I wonder if this idea could work as implementation for the free() function:
typedef struct _mem_dictionary
{
void *addr;
size_t size;
} mem_dictionary;
mem_dictionary *dictionary = NULL; //array of memory dictionaries
int dictionary_ct = 0; //dictionary struct counter
void *malloc(size_t size)
{
void *return_ptr = (void *) sbrk(size);
if (dictionary == NULL)
dictionary = (void *) sbrk(1024 * sizeof(mem_dictionary));
dictionary[dictionary_ct].addr = return_ptr;
dictionary[dictionary_ct].size = size;
dictionary_ct++;
printf("malloc(): %p assigned memory\n",return_ptr);
return return_ptr;
}
void free(void *ptr)
{
size_t i;
int flag = 0;
for(i = 0; i < dictionary_ct ; i++){
if(dictionary[i].addr == ptr){
dictionary[i].addr=NULL;
dictionary[i].size = 0;
flag = 1;
break;
}
}
if(!flag){
printf("Remember to free!\n");
}
}
Thanks in advance!
No, it will not. The address you are "freeing" is effectively lost after such a call. How would you ever know that the particular chunk of memory is again available for allocation?
There has been a lot of research in this area, here is some overview - Fast Memory Allocation in Dr. Dobbs.
Edit 0:
You are wrong about sbrk(2) - it's not a "better malloc" and you cannot use it as such. That system call modifies end of process data segment.
Few things:
Where do you allocate the memory for the dictionary?
How do you allocate the memory that dictionary->addr is pointing at? Without having the code for your malloc it is not visible if your free would work.
Unless in your malloc function you're going through each and every memory address available to the process to check if it is not used by your dictionary, merely the assignment dictionary[i].addr=NULL would not "free" the memory, and definitely not keep it for reuse.
BTW, the printf function in your version of free would print Remember to free! when the user calls free on a pointer that is supposedly not allocated, right? Then why "remember to free"?
Edit:
So with that malloc function, no, your free does not free the memory. First of all, you're losing the address of the memory, so every time you call this malloc you're actually pushing the process break a little further, and never reuse freed memory locations. One way to solve this is to somehow keep track of locations that you have "freed" so that next time that malloc is called, you can check if you have enough available memory already allocated to the process, and then reuse those locations. Also, remember that sbrk is a wrapper around brk which is an expensive system call, you should optimize your malloc so that a big chunk of memory is requested from OS using sbrk and then just keep track of which part you're using, and which part is available.

Checking if a pointer is allocated memory or not

Can we check whether a pointer passed to a function is allocated with memory or not in C?
I have wriiten my own function in C which accepts a character pointer - buf [pointer to a buffer] and size - buf_siz [buffer size]. Actually before calling this function user has to create a buffer and allocate it memory of buf_siz.
Since there is a chance that user might forget to do memory allocation and simply pass the pointer to my function I want to check this. So is there any way I can check in my function to see if the pointer passed is really allocated with buf_siz amount of memory .. ??
EDIT1: It seems there is no standard library to check it .. but is there any dirty hack to check it .. ??
EDIT2: I do know that my function will be used by a good C programmer ... But I want to know whether can we check or not .. if we can I would like to hear to it ..
Conclusion: So it is impossible to check if a particular pointer is allocated with memory or not within a function
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.)
The below code is what I have used once to check if some pointer tries to access illegal memory. The mechanism is to induce a SIGSEGV. The SEGV signal was redirected to a private function earlier, which uses longjmp to get back to the program. It is kind of a hack but it works.
The code can be improved (use 'sigaction' instead of 'signal' etc), but it is just to give an idea. Also it is portable to other Unix versions, for Windows I am not sure. Note that the SIGSEGV signal should not be used somewhere else in your program.
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <signal.h>
jmp_buf jump;
void segv (int sig)
{
longjmp (jump, 1);
}
int memcheck (void *x)
{
volatile char c;
int illegal = 0;
signal (SIGSEGV, segv);
if (!setjmp (jump))
c = *(char *) (x);
else
illegal = 1;
signal (SIGSEGV, SIG_DFL);
return (illegal);
}
int main (int argc, char *argv[])
{
int *i, *j;
i = malloc (1);
if (memcheck (i))
printf ("i points to illegal memory\n");
if (memcheck (j))
printf ("j points to illegal memory\n");
free (i);
return (0);
}
For a platform-specific solution, you may be interested in the Win32 function IsBadReadPtr (and others like it). This function will be able to (almost) predict whether you will get a segmentation fault when reading from a particular chunk of memory.
However, this does not protect you in the general case, because the operating system knows nothing of the C runtime heap manager, and if a caller passes in a buffer that isn't as large as you expect, then the rest of the heap block will continue to be readable from an OS perspective.
I always initialize pointers to null value. Therefore when I allocate memory it will change. When I check if memory's been allocated I do pointer != NULL. When I deallocate memory I also set pointer to null. I can't think of any way to tell if there was enough memory allocated.
This doesn't solve your problem, but you got to trust that if someone writes C programs then he is skilled enough to do it right.
I once used a dirty hack on my 64bit Solaris. In 64bit mode the heap starts at 0x1 0000 0000. By comparing the pointer I could determine if it was a pointer in the data or code segment p < (void*)0x100000000, a pointer in the heap p > (void*)0x100000000 or a pointer in a memory mapped region (intptr_t)p < 0 (mmap returns addresses from the top of the addressable area).
This allowed in my program to hold allocated and memory mapped pointers in the same map, and have my map module free the correct pointers.
But this kind of trick is highly unportable and if your code relies on something like that, it is time to rethink the architecture of your code. You're probably doing something wrong.
I know this is an old question, but almost anything is possible in C. There are a few hackish solutions here already, but a valid way of determining if memory has been properly allocated is to use an oracle to take the place of malloc, calloc, realloc, and free. This is the same way testing frameworks (such as cmocka) can detect memory problems (seg faults, not freeing memory, etc.). You can maintain a list of memory addresses allocated as they are allocated and simply check this list when the user wants to use your function. I implemented something very similar for my own testing framework. Some example code:
typedef struct memory_ref {
void *ptr;
int bytes;
memory_ref *next;
}
memory_ref *HEAD = NULL;
void *__wrap_malloc(size_t bytes) {
if(HEAD == NULL) {
HEAD = __real_malloc(sizeof(memory_ref));
}
void *tmpPtr = __real_malloc(bytes);
memory_ref *previousRef = HEAD;
memory_ref *currentRef = HEAD->next;
while(current != NULL) {
previousRef = currentRef;
currentRef = currentRef->next;
}
memory_ref *newRef = (memory_ref *)__real_malloc(sizeof(memory_ref));
*newRef = (memory_ref){
.ptr = tmpPtr,
.bytes = bytes,
.next = NULL
};
previousRef->next = newRef;
return tmpPtr;
}
You would have similar functions for calloc, realloc, and free, each wrapper prefixed with __wrap_. The real malloc is available through the use of __real_malloc (similar for the other functions you are wrapping). Whenever you want to check if memory is actually allocated, simply iterate over the linked memory_ref list and look for the memory address. If you find it and it's big enough, you know for certain the memory address won't crash your program; otherwise, return an error. In the header file your program uses, you would add these lines:
extern void *__real_malloc (size_t);
extern void *__wrap_malloc (size_t);
extern void *__real_realloc (size_t);
extern void *__wrap_realloc (size_t);
// Declare all the other functions that will be wrapped...
My needs were fairly simple so I implemented a very basic implementation, but you can imagine how this could be extended to have a better tracking system (e.g. create a struct that keeps track of the memory location in addition to the size). Then you simply compile the code with
gcc src_files -o dest_file -Wl,-wrap,malloc -Wl,-wrap,calloc -Wl,-wrap,realloc -Wl,-wrap,free
The disadvantage is the user has to compile their source code with the above directives; however, it's far from the worse I have seen. There is some overhead to allocating and freeing memory, but there is always some overhead when adding security.
No, in general there is no way to do this.
Furthermore, if your interface is just "pass a pointer to a buffer where I will put stuff", then the caller may choose not to allocate memory at all, and instead use a fixed size buffer that's statically allocated or an automatic variable or something. Or perhaps it's a pointer into a portion of a larger object on the heap.
If your interface specifically says "pass a pointer to allocated memory (because I'm going to deallocate it)", then you should expect that the caller will do so. Failure to do so isn't something you can reliably detect.
One hack you can try is checking if your pointer points to stack allocated memory.
This will not help you in general as the allocated buffer might be to small or the pointer points to some global memory section (.bss, .const, ...).
To perform this hack, you first store the address of the first variable in main(). Later, you can compare this address with the address of a local variable in your specific routine.
All addresses between both addresses are located on the stack.
Well, I don't know if somebody didn't put it here already or if it will be a possibility in your programme. I was struggling with similar thing in my university project.
I solved it quite simply - In initialization part of main() , after I declared LIST *ptr, I just put that ptr=NULL. Like this -
int main(int argc, char **argv) {
LIST *ptr;
ptr=NULL;
So when allocation fails or your pointer isn't allocated at all, it will be NULL. SO you can simply test it with if.
if (ptr==NULL) {
"THE LIST DOESN'T EXIST"
} else {
"THE LIST MUST EXIST --> SO IT HAS BEEN ALLOCATED"
}
I don't know how your programme is written, but you surely understand what am I trying to point out. If it is possible to check like this your allocation and then pass your arguments to you function, you could have a simple solution.
Of course you must be careful to have your functions with allocating and creating the structure done well but where in C you don't have to be careful.
I don't know a way of doing it from a library call, but on Linux, you can look at /proc/<pid>/numa_maps. It will show all sections of memory and the third column will say "heap" or "stack". You can look at the raw pointer value to see where it lines up.
Example:
00400000 prefer:0 file=/usr/bin/bash mapped=163 mapmax=9 N0=3 N1=160
006dc000 prefer:0 file=/usr/bin/bash anon=1 dirty=1 N0=1
006dd000 prefer:0 file=/usr/bin/bash anon=9 dirty=9 N0=3 N1=6
006e6000 prefer:0 anon=6 dirty=6 N0=2 N1=4
01167000 prefer:0 heap anon=122 dirty=122 N0=25 N1=97
7f39904d2000 prefer:0 anon=1 dirty=1 N0=1
7f39904d3000 prefer:0 file=/usr/lib64/ld-2.17.so anon=1 dirty=1 N0=1
7f39904d4000 prefer:0 file=/usr/lib64/ld-2.17.so anon=1 dirty=1 N1=1
7f39904d5000 prefer:0 anon=1 dirty=1 N0=1
7fffc2d6a000 prefer:0 stack anon=6 dirty=6 N0=3 N1=3
7fffc2dfe000 prefer:0
So pointers that are above 0x01167000 but below 0x7f39904d2000 are located in the heap.
You can't check with anything available in standard C. Even if your specific compiler were to provide a function to do so, it would still be a bad idea. Here's an example of why:
int YourFunc(char * buf, int buf_size);
char str[COUNT];
result = YourFunc(str, COUNT);
As everyone else said, there isn't a standard way to do it.
So far, no-one else has mentioned 'Writing Solid Code' by Steve Maguire. Although castigated in some quarters, the book has chapters on the subject of memory management, and discusses how, with care and complete control over all memory allocation in the program, you can do as you ask and determine whether a pointer you are given is a valid pointer to dynamically allocated memory. However, if you plan to use third party libraries, you will find that few of them allow you to change the memory allocation routines to your own, which greatly complicates such analysis.
in general lib users are responsible for input check and verification. You may see ASSERT or something in the lib code and they are used only for debug perpose. it is a standard way when writing C/C++. while so many coders like to do such check and verfying in their lib code very carefully. really "BAD" habits. As stated in IOP/IOD, lib interfaces should be the contracts and make clear what will the lib do and what will not, and what a lib user should do and what should be not necessary.
There is a simple way to do this. Whenever you create a pointer, write a wrapper around it. For example, if your programmer uses your library to create a structure.
struct struct_type struct_var;
make sure he allocates memory using your function such as
struct struct_type struct_var = init_struct_type()
if this struct_var contains memory that is dynamically allocated, for ex,
if the definition of struct_type was
typedef struct struct_type {
char *string;
}struct_type;
then in your init_struct_type() function, do this,
init_struct_type()
{
struct struct_type *temp = (struct struct_type*)malloc(sizeof(struct_type));
temp->string = NULL;
return temp;
}
This way,unless he allocates the temp->string to a value, it will remain NULL. You can check in the functions that use this structure, if the string is NULL or not.
One more thing, if the programmer is so bad, that he fails to use your functions, but rather directly accesses unallocated the memory, he doesn't deserve to use your library. Just ensure that your documentation specifies everything.
No, you can't. You'll notice that no functions in the standard library or anywhere else do this. That's because there's no standard way to tell. The calling code just has to accept responsibility for correctly managing the memory.
An uninitialised pointer is exactly that - uninitialised. It may point to anything or simply be an invalid address (i.e. one not mapped to physical or virtual memory).
A practical solution is to have a validity signature in the objects pointed to. Create a malloc() wrapper that allocates the requested block size plus the sizeof a signature structure, creates a signature structure at the start of the block but returns the pointer to the location after the signature. You can then create a validation function that takes the pointer, uses a negative offset to get the validity structure and checks it. You will of course need a corresponding free() wrapper to invalidate the block by overwriting the validity signature, and to perform the free from the true start of the allocated block.
As a validity structure, you might use the size of the block and its one's complement. That way you not only have a way of validating the block (XOR the two values and compare to zero), but you also have information about the block size.
A pointer tracker, tracks and checks the validity of a pointer
usage:
create memory int * ptr = malloc(sizeof(int) * 10);
add the pointer address to the tracker Ptr(&ptr);
check for failing pointers PtrCheck();
and free all trackers at the end of your code
PtrFree();
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
struct my_ptr_t { void ** ptr; size_t mem; struct my_ptr_t *next, *previous; };
static struct my_ptr_t * ptr = NULL;
void Ptr(void * p){
struct my_ptr_t * tmp = (struct my_ptr_t*) malloc(sizeof(struct my_ptr_t));
printf("\t\tcreating Ptr tracker:");
if(ptr){ ptr->next = tmp; }
tmp->previous = ptr;
ptr = tmp;
ptr->ptr = p;
ptr->mem = **(size_t**) ptr->ptr;
ptr->next = NULL;
printf("%I64x\n", ptr);
};
void PtrFree(void){
if(!ptr){ return; }
/* if ptr->previous == NULL */
if(!ptr->previous){
if(*ptr->ptr){
free(ptr->ptr);
ptr->ptr = NULL;
}
free(ptr);
ptr = NULL;
return;
}
struct my_ptr_t * tmp = ptr;
for(;tmp != NULL; tmp = tmp->previous ){
if(*tmp->ptr){
if(**(size_t**)tmp->ptr == tmp->mem){
free(*tmp->ptr);
*tmp->ptr = NULL;
}
}
free(tmp);
}
return;
};
void PtrCheck(void){
if(!ptr){ return; }
if(!ptr->previous){
if(*(size_t*)ptr->ptr){
if(*ptr->ptr){
if(**(size_t**) ptr->ptr != ptr->mem){
printf("\tpointer %I64x points not to a valid memory address", ptr->mem);
printf(" did you freed the memory and not NULL'ed the pointer or used arthmetric's on pointer %I64x?\n", *ptr->ptr);
return;
}
}
return;
}
return;
}
struct my_ptr_t * tmp = ptr;
for(;tmp->previous != NULL; tmp = tmp->previous){
if(*(size_t*)tmp->ptr){
if(*tmp->ptr){
if(**(size_t**) tmp->ptr != tmp->mem){
printf("\tpointer %I64x points not to a valid memory address", tmp->mem);
printf(" did you freed the memory and not NULL'ed the pointer or used arthmetric's on pointer %I64x?\n", *tmp->ptr); continue;
}
}
continue;
}
}
return;
};
int main(void){
printf("\n\n\t *************** Test ******************** \n\n");
size_t i = 0;
printf("\t *************** create tracker ********************\n");
int * ptr = malloc(sizeof(int) * 10);
Ptr(&ptr);
printf("\t *************** check tracker ********************\n");
PtrCheck();
printf("\t *************** free pointer ********************\n");
free(ptr);
printf("\t *************** check tracker ********************\n");
PtrCheck();
printf("\t *************** set pointer NULL *******************\n");
ptr = NULL;
printf("\t *************** check tracker ********************\n");
PtrCheck();
printf("\t *************** free tracker ********************\n");
PtrFree();
printf("\n\n\t *************** single check done *********** \n\n");
printf("\n\n\t *************** start multiple test *********** \n");
int * ptrs[10];
printf("\t *************** create trackers ********************\n");
for(; i < 10; i++){
ptrs[i] = malloc(sizeof(int) * 10 * i);
Ptr(&ptrs[i]);
}
printf("\t *************** check trackers ********************\n");
PtrCheck();
printf("\t *************** free pointers but set not NULL *****\n");
for(i--; i > 0; i-- ){ free(ptrs[i]); }
printf("\t *************** check trackers ********************\n");
PtrCheck();
printf("\t *************** set pointers NULL *****************\n");
for(i=0; i < 10; i++){ ptrs[i] = NULL; }
printf("\t *************** check trackers ********************\n");
PtrCheck();
printf("\t *************** free trackers ********************\n");
PtrFree();
printf("\tdone");
return 0;
}
I'm not sure how fast msync is, but this is a linux only solution:
// Returns 1 if the ponter is mapped
int pointer_valid (void *p)
{
size_t pg_size = sysconf (_SC_PAGESIZE);
void *pg_start = (void *) ((((size_t)p) / pg_size) * pg_size);
return msync (pg_start, pg_size, MS_ASYNC) == 0;
}
There is almost never "never" in computers. Cross platform is way over anticipated. After 25 years I have worked on hundreds of projects all anticipating cross platform and it never materialized.
Obviously, a variable on the stack, would point to an area on the stack, which is almost linear. Cross platform garbage collectors work, by marking the top or (bottom) of the stack, calling a little function to check if the stack grows upwards or downwards and then checking the stack pointer to know how big the stack is. This is your range. I don't know a machine that doesn't implement a stack this way (either growing up or down.)
You simply check if the address of our object or pointer sits between the top and bottom of the stack. This is how you would know if it is a stack variable.
Too simple. Hey, is it correct c++? No. Is correct important? In 25 years I have seen way more estimation of correct. Well, let's put it this way: If you are hacking, you aren't doing real programming, you are probably just regurigating something that's already been done.
How interesting is that?

Resources