1

I have just started learning about virtual memory and I don't understand if I can see the memory that I have allocated with mmap(). The 2 show_maps() print the same text. Shouldn't I also see the allocated memory from mmap() in the second show_maps() and if not is there a way to see it?

#define MAPS_PATH        "/proc/self/maps"
#define LINELEN          256

void show_maps(void)
{
    FILE *f;
    char line[LINELEN];

    f = fopen(MAPS_PATH, "r");
    if (!f) {
        printf("Cannot open " MAPS_PATH ": %s\n", strerror(errno));
        return;
    }

    printf("\nVirtual Memory Map of process [%ld]:\n", (long)getpid());
    while (fgets(line, LINELEN, f) != NULL) {
        printf("%s", line);
    }
    printf("--------------------------------------------------------\n\n");

    if (0 != fclose(f))
        perror("fclose(" MAPS_PATH ")");
}

int main(void)
{
    pid_t mypid;
    int fd = -1;
    uint64_t *pa;

    mypid = getpid();

    show_maps();
   
    pa=mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    
    show_maps();
}
Runner
  • 11
  • 1
  • _"if not is there a way to see it?"_ Take a look at [this](https://phoenixnap.com/kb/linux-commands-check-memory-usage). Also, don't forget to [do this](https://stackoverflow.com/a/6979904/645128) – ryyker Jun 06 '22 at 16:57

1 Answers1

0

You did:

pa = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

If you check the value of pa, you'll find that it is MAP_FAILED

So, the actual mapping did not occur.

This is because you called mmap with an fd value of -1. So, the call had no backing store/file.

To fix this, add MAP_ANONYMOUS:

pa = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS,fd,0); 
Craig Estey
  • 30,627
  • 4
  • 24
  • 48