Skip to content

Commit 02fe517

Browse files
authored
Fix that malloc() doesn't return a null pointer for too large allocations
The _sbrk() function wasn't implemented. It's used by malloc() to request more heap memory. This function must be defined and correctly implemented if we want malloc() to return a null pointer if more space is requested than is available. It already works that way for the Mbed Core (although with a different implementation), but doesn't for the Renesas Core before this addition.
1 parent 2e56526 commit 02fe517

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

cores/arduino/main.cpp

+33-1
Original file line numberDiff line numberDiff line change
@@ -145,4 +145,36 @@ extern "C" __attribute__((weak)) void __cxa_pure_virtual(void);
145145
extern "C" __attribute__((weak)) void __cxa_pure_virtual(void)
146146
{
147147
exit(1);
148-
}
148+
}
149+
150+
// Used by malloc() to request more heap memory. This function
151+
// must be defined if we want malloc() to return a null pointer
152+
// if more space is requested than is available. Notice that
153+
// there's no support for decrement as the very first action,
154+
// because the result of that is unspecified by the standard,
155+
// so we can do whatever we want in that case.
156+
extern "C" void * _sbrk(ptrdiff_t change)
157+
{
158+
extern char __HeapBase; // From the linker script
159+
extern char __HeapLimit; // From the linker script
160+
static char *programBreak = nullptr;
161+
162+
// If malloc() hasn't been called before, then set the program break
163+
// to __HeapBase from the linker script
164+
if (nullptr == programBreak)
165+
{
166+
programBreak = &__HeapBase;
167+
}
168+
// We must return the old program break if everything is ok, so save it
169+
char * const oldProgramBreak = programBreak;
170+
// Check that the new program break doesn't pass __HeapLimit from the
171+
// linker script
172+
if ((programBreak + change) > &__HeapLimit)
173+
{
174+
return (void *) -1;
175+
}
176+
// Update the program break according to the requested amount of heap
177+
// memory
178+
programBreak += change;
179+
return oldProgramBreak;
180+
}

0 commit comments

Comments
 (0)