Reputation: 7772
I am currently doing a memory allocator for a C project and I am facing something that I don't understand
I'm calling mmap to reserve the heap for my program where i will put some headers.
I have
void * START_ADDRESS;
int MEMORY_INITIALIZED;
void* Mem_Init(int sizeOfRegion){
START_ADDRESS = mmap(NULL, sizeOfRegion, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_FILE |MAP_PRIVATE, -1,0);
header_t* startingHeader = START_ADDRESS;
//rest of the fontion
}
void* Mem_Alloc(int size){
if(MEMORY_INITIALIZED==0){
START_ADDRESS= Mem_Init(size);
//rest of the funtion
}
When i use the errno on this code it returns me the invalid Argument error.
Why do mmap returns a valid adress when i call it using the Mem_Init method and why do it returns me invalidArgument when i call Mem_Init in the Mem_Alloc method ?
Thanks in advance
Upvotes: 1
Views: 4555
Reputation: 7772
I finally found the error.
In the test program the teacher gave us, he tried to allocate a 0 size header, and mmap fails when you try to alocate a null pointer.
A simple correction was
void* Mem_Init(int sizeOfRegion){
if(sizeOfRegion==0) sizeOfRegion = 1024; //1024 is an exemple
START_ADDRESS = mmap(NULL, sizeOfRegion, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_FILE |MAP_PRIVATE, -1,0);
if ((void *) -1 == START_ADDRESS) {
printf("Could not map memory: %s\n", strerror(errno));
}
Thanks for the support guys
Upvotes: 1
Reputation:
With some minor changes, your code appears to work:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
void * START_ADDRESS;
int MEMORY_INITIALIZED = 0;
void* Mem_Init(int sizeOfRegion){
START_ADDRESS = mmap(NULL, sizeOfRegion, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_FILE |MAP_PRIVATE, -1,0);
if ((void *) -1 == START_ADDRESS) {
printf("Could not map memory: %s\n", strerror(errno));
}
printf("%p\n", START_ADDRESS);
void* startingHeader = START_ADDRESS;
//rest of the fontion
return startingHeader;
}
void* Mem_Alloc(int size){
if(MEMORY_INITIALIZED==0){
START_ADDRESS= Mem_Init(size);
}
//rest of the funtion
return START_ADDRESS;
}
int main(void) {
Mem_Alloc(1024);
return 0;
}
Compiled using
gcc -Wall -Werror -o code code.c
I thought the most important change is that MEMORY_INITIALIZED is set to 0, but the language lawyers assure me that this is already done by compilers that follow the C89 standard.
Upvotes: 2