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,.