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(); } 
1
  • "if not is there a way to see it?" Take a look at this. Also, don't forget to do this Commented Jun 6, 2022 at 16:57

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.