stevethese
Member
Hi, I'm working on a project which utilises a lot of dynamic memory allocation. I want to be able to detect when there's none left. Logically, I supposed that calling malloc() might just return a NULL pointer if there is no more ram. Instead however, it appears to allocate me ram which was already in use, leading to crashes.
I made a simple example sketch to demonstrate this:
The sketch repeatedly tries to allocate one byte, and reports to the user each time it does this successfully. If it receives a NULL pointer instead, it reports this. However, when I try running this sketch, no NULL pointers are reported, and instead the sketch successfully makes 3825 allocations, and then stops responding - presumably having ended up overwriting something it shouldn't have.
Is there a way to stop this from happening, and somehow figure out that point where no more malloc()'s can be called?
Another question - I made another edit to the code to give me some more info, which indicated that each of the malloc(1)'s called was in fact allocating 16 bytes - hence giving me under 4,000 of them despite the Teensy 3.1's 65,536 byte memory. Is this expected? Shouldn't a malloc(1) allocate just one byte?
Thanks
I made a simple example sketch to demonstrate this:
Code:
void* pointer;
uint32_t counter = 0;
void setup() {
delay(1000);
}
void loop() {
pointer = malloc(1);
counter++;
if (pointer == NULL) Serial.println("got null");
else Serial.println(String(counter) + " allocations made");
}
The sketch repeatedly tries to allocate one byte, and reports to the user each time it does this successfully. If it receives a NULL pointer instead, it reports this. However, when I try running this sketch, no NULL pointers are reported, and instead the sketch successfully makes 3825 allocations, and then stops responding - presumably having ended up overwriting something it shouldn't have.
Is there a way to stop this from happening, and somehow figure out that point where no more malloc()'s can be called?
Another question - I made another edit to the code to give me some more info, which indicated that each of the malloc(1)'s called was in fact allocating 16 bytes - hence giving me under 4,000 of them despite the Teensy 3.1's 65,536 byte memory. Is this expected? Shouldn't a malloc(1) allocate just one byte?
Thanks