Why does mmap return an invalid address but not an error code?

40 Views Asked by At

In this small program I am attempting to write to a file using mmap.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <fcntl.h>
#include <assert.h>
#include <pthread.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>

typedef struct stat stat_t;

int main() {
    int total_size = 10;
    int fd = open("res.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        perror("open() Program failure");
    }
    char *res_ptr = mmap(NULL, total_size, PROT_WRITE, MAP_SHARED, fd, 0);
    if(res_ptr == MAP_FAILED) {
        printf("Error Number  mmap %d\n", errno);
        perror("mmap() Program failure");
    }

    memcpy(res_ptr, "ASDFG", 5);
    munmap(res_ptr, total_size);
    close(fd);
    return 0;
}

Neither open nor mmap return an error, but mmap seems to be returning an invalid or nonexistent address.

The eclipse debugger says that it can't access that memory address. enter image description here

Finally, the attempt to execute write something to that address with memcpy causes a Bus error. enter image description here

So, why did mmap return this apparently invalid address?

0

There are 0 best solutions below