The HyperNews Linux KHG Discussion Pages

Question: What about mprotect?

Forum: The Linux Kernel Hackers' Guide
Re: Question Does MMAP work with Redhat 4.2? (Guy)
Re: Yes, it works just fine. (Michael K. Johnson)
Keywords: MMAP memory error
Date: Fri, 17 Jul 1998 04:48:53 GMT
From: Sengan Baring-Gould <unknown>

If I use the example given by man mprotect on Redhat 4.2, the
program does not run:

./mprotect 

Couldn't mprotect: Invalid argument

Why?

Thanks,

Sengan

       #include <stdio.h>
       #include <stdlib.h>
       #include <errno.h>
       #include <sys/mman.h>

       int
       main(void)
       {
           char *p;
           char c;

           /* Allocate a buffer; it will have the default
              protection of PROT_READ|PROT_WRITE. */
           p = malloc(1024);
           if (!p) {
               perror("Couldn't malloc(1024)");
               exit(errno);
           }

           c = p[666];         /* Read; ok */
           p[666] = 42;        /* Write; ok */

           /* Mark the buffer read-only. */
           if (mprotect(p, 1024, PROT_READ)) {
               perror("Couldn't mprotect");
               exit(errno);
           }

           c = p[666];         /* Read; ok */
           p[666] = 42;        /* Write; program dies on SIGSEGV */

           exit(0);
       }