Showing results for 
Search instead for 
Did you mean: 
Honored Contributor I

Malloc till it fails, crashes, bug in Malloc?

I'm trying to write some code that will determin how much "free" memory the system still has. I created some somewhat speedy code, but really the simple code could just run a loop like this: 



uint32_t FreeMemory(void) 

uint8_t *ptr; 

uint32_t counter = 1; 


ptr = malloc(counter) 

while (ptr != NULL) 


free (ptr); 

ptr = malloc(counter); 


return counter; 


This can run a few times, but eventually the system crashes because of this. 

I have tried disabeling interupts, but it still crashes. 


Is there a bug with malloc? (new crashes as well) 


Or is this not possible to do? I realize I'm nearly using all free memory, but I also free it as soon as the function is finished? 


I really want some code that can run in the background to make sure they system does not have any memory leaks. This code is not running on any operating system. 


Anyone with expreince with this? 


0 Kudos
4 Replies
Honored Contributor I

If you want to know how much memory malloc can give you, you are probably better off looking at how malloc is implemented and then scanning the internal structure. 


You might find that malloc eventually hits the stack.
Honored Contributor I

Well, I think it does hit the stack. BUT I'm not doing anything with the data, just "allocating" it and then deleting it. It doesn't seem like this should crash the CPU. 


I will look into what you suggested though, seems reasonable. 


I started looking at mallinfo() so far uordblks is somewhat useful as it lets me know how much memory is allocated, but I don't see anyway of determining how much is left? 


It bothers me that this crashes... shouldn't crash.
Honored Contributor I

That last free in your function should be wrapped with an if statement guarding it from trying to free an unallocated pointer. I suspect you are running into a stack and heap collision like DSL warned you of. 


A common way for detecting a stack and heap collision is to fill your memory with some known pattern (you pick), then populate it with your code, run the code, then take a look at the memory after to see if your pattern is still around. If the pattern is gone then there was most likely a stack + heap collision.
Honored Contributor I

I have defined linker script for my code.  


When I call malloc() NIOS returns me a address from some other region instead of .heap region. 



Please let me know how can I allocate memory to pointers from the heap as defined in the GUI of BSP Editor. As in theory malloc() gives memory from heap.