I'm trying to implement malloc
on CentOS, but I keep getting the error:
malloc.c: In function ‘malloc’:
malloc.c:11:5: error: implicit declaration of function ‘sbrk’ [-Werror=implicit-function-declaration]
mem_ptr = sbrk(SIXTY_FOUR_K); /* Allocate 64 kB of memory */
Here is the code that the compiler warning is referencing:
#include "malloc.h"
#include <unistd.h>
void * malloc(size_t bytes) {
uintptr_t mem_ptr;
if (bytes <= 0) { /* If user passes in bad value, return NULL */
return NULL;
}
mem_ptr = sbrk(SIXTY_FOUR_K); /* Allocate 64 kB of memory */
if (mem_ptr == -1) { /* sbrk() failed */
return NULL;
}
return (void *)mem_ptr;
}
According to the documentation on sbrk
, you should just have to import unistd.h
, which I do. Is there something I'm doing wrong?
Did you take a look at the Feature Test Macro requirements?
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
brk(), sbrk(): Since glibc 2.12: _BSD_SOURCE || _SVID_SOURCE || (_XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) && !(_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) Before glibc 2.12: _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
See if compiling with something like -D_SVID_SOURCE
will work (though it looks like there are a number of options based on that macro list)
As of glibc 2.19, a new feature test macro was added, _DEFAULT_SOURCE
which is meant to replace _BSD_SOURCE
and _SVID_SOURCE
. For more information on _DEFAULT_SOURCE
, see this question: What does -D_DEFAULT_SOURCE do?