The mremap function could not allocate new memory

I am writing the following code, but the code still gave me an EEERROR message stating that mremap could not expand the memory.

 int main() { int size_of_mem = 1024 int fd = shm_open("/myregion", O_CREAT | O_RDWR, S_IRWXO | S_IRUSR | S_IWUSR); if (fd == -1) printf("ERROR in shm_open \n") ; if (ftruncate(fd, size_of_mem) == -1) printf("ERROR in ftruncate \n") ; int shm_address = mmap(0 , size_of_mem , PROT_READ | PROT_WRITE | PROT_EXEC ,MAP_SHARED , fd , 0) ; if (shm_address == MAP_FAILED) { printf("Error mmapping the file \n"); exit(EXIT_FAILURE); } int temp = mremap(shm_address , size_of_mem ,4000 , MREMAP_MAYMOVE) ; if( temp < 0) { printf("EEEEEEEERROR\n") ; } return 0 ; } 
0
source share
1 answer

There are a couple of things.

First , mmap() and mremap() return a void* pointer, which you should not just discard on int .

Second , mremap() man page :

RETURN VALUE

If successful, mremap () returns a pointer to a new region of virtual memory. On error, the value MAP_FAILED is returned (i.e. (void *) -1), and errno is set accordingly.

So your check temp < 0 incorrect. It should be temp == (void*)-1 . It is possible that mremap() returns a valid success pointer that is less than zero when converting to int.

Third , both mmap() and mremap() set errno ( man ) when an error occurs. You can read this to get more information on what exactly went wrong. To simply display a text error message, use the perror() function ( man page ). Please note that for this you need #include <errno.h> .

Fourth , if you find an error condition, you always print a message, but in most cases you can continue execution. It does not make sense. If shm_open() fails, you should return immediately (or call exit(EXIT_FAILURE) ). None of the following functions will work if you cannot even open the SHM file.

So my cleaned version is as follows:

 #include <error.h> int main() { int size_of_mem = 1024; int fd = shm_open("/myregion", O_CREAT | O_RDWR, S_IRWXO | S_IRUSR | S_IWUSR); if (fd == -1) { perror("Error in shm_open"); return EXIT_FAILURE; } if (ftruncate(fd, size_of_mem) == -1) { perror("Error in ftruncate"); return EXIT_FAILURE; } void *shm_address = mmap(0, size_of_mem, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_SHARED, fd, 0); if (shm_address == MAP_FAILED) { perror("Error mmapping the file"); return EXIT_FAILURE; } void *temp = mremap(shm_address, size_of_mem, 4000, MREMAP_MAYMOVE); if(temp == (void*)-1) { perror("Error on mremap()"); return EXIT_FAILURE; } return 0; } 

Note:

  • Fix data types ( void* ), fix error checking for mremap() , use perror() to print more informative error messages, error paths complete the function.
  • Correct / consistent indentation.
  • There are no spaces in function calls before,.
+4
source

Source: https://habr.com/ru/post/1259206/


All Articles