This is the mail archive of the
mailing list for the newlib project.
RE: sprintf() heap usage
- From: Sandeep Kumar Singh <Sandeep dot Singh2 at kpitcummins dot com>
- To: Vasili Galka <vvv444 at gmail dot com>
- Cc: "newlib at sourceware dot org" <newlib at sourceware dot org>, Cecilia Rodrigues <Cecilia dot Rodrigues at kpitcummins dot com>, Kaushik Phatak <Kaushik dot Phatak at kpitcummins dot com>, "Vinay Kumar. G" <Vinay dot G at kpitcummins dot com>
- Date: Tue, 16 Jul 2013 14:08:56 +0000
- Subject: RE: sprintf() heap usage
- References: <CA+gZxsO8PrqwaTU-xMJ1QrOvz3otf_uVt2ap-wGtdKj7niX7GQ at mail dot gmail dot com>
As per my knowledge, heap always take the space at the end of RAM after the
other sections. The area assigned to RAM in linker script will be used by .data
and .bss sections. The rest of RAM will be used by the stack and heap sections.
As the amount of area used by stack and heap will depend on the test-case; they
won't be specified in linker script and hence can use the entire area of RAM.
The stack and heap size are not fixed. The stack grows downwards towards the
heap space, and the heap grows upwards towards the stack. If the stack space
grows beyond its boundary and occupies the heap space then the error condition
is called stack-heap Collision Error.
Heap and stack collision is detected in "sbrk" function which is invoked by
"malloc", internally. This function expects that heap area is always between
"bss" and "stack" sections.
You can also check this is the definition of "sbrk" function.
register char *stack_ptr asm ("sp");
caddr_t sbrk(int incr)
extern char end; /* Defined by the linker */
static char *heap_end;
if (heap_end == 0)
heap_end = &end;
prev_heap_end = heap_end;
if (heap_end + incr > stack_ptr)
//printf("Heap and Stack Collision occured\n\r");
heap_end += incr;
The condition "if (heap_end + incr > stack_ptr)" detects the heap and stack
collision. We can also change these boundaries as per our requirement.
Sandeep Kumar Singh,
KPIT Cummins InfoSystems Ltd.
> -----Original Message-----
> From: email@example.com [mailto:firstname.lastname@example.org]
> On Behalf Of Vasili Galka
> Sent: Tuesday, July 16, 2013 3:09 PM
> To: email@example.com
> Subject: sprintf() heap usage
> I've been surprised to discover that using sprintf() leads to
> requirement of sbrk(). Can anyone please explain me why?
> For gods sake, the function already has output buffer provided. The
> lifetime of the function is well defined and it has stack. Why would
> it require heap!?
> Vasili Galka