malloc always returns null

Duane Ellis duane-gcc-help@duaneellis.com
Sun Jul 20 02:44:00 GMT 2008


ted> I'm attempting to configure the gcc 4.0.3 tool chain to compile c++ 
source on an ARM 9 (ARM926-ejs) target.  At this point, everything seems 
to be working except malloc:  It always returns the null pointer.

You do not state what you are using as your "standard C library". I 
assume "newlib" it is the most common embedded C library.

NEWLIB requires the underlying function: "_sbrk" - in syscalls, In "OS" 
type environment, SBRK would call the operating system requesting more 
memory.

In an embedded system using NEWLIB - the SBRK function has (a) a pointer 
to the current end of the heap, it sort of works like this:
Newlib impliments it this way:  (newlib source, libgloss, arm, syscalls.c)

You want to set a break point at _sbrk - and step through the code.
Examine the addresses of variables as you do this.

caddr_t
_sbrk (int incr)
{
  extern char end asm ("end"); /* Defined by the linker.  */
  static char * heap_end;
  char * prev_heap_end;

  if (heap_end == NULL)
    heap_end = & end;
 
  prev_heap_end = heap_end;
 
  if (heap_end + incr > stack_ptr)
    {
      /* Some of the libstdc++-v3 tests rely upon detecting
     out of memory errors, so do not abort here.  */
#if 0
      extern void abort (void);

      _write (1, "_sbrk: Heap and stack collision\n", 32);
     
      abort ();
#else
      errno = ENOMEM;
      return (caddr_t) -1;
#endif
    }
 
  heap_end += incr;

  return (caddr_t) prev_heap_end;
}    



More information about the Gcc-help mailing list