作業系統›Ch7 記憶體管理第 29 題/共 40 題
29. mprotect、Memory Protection、Heap Allocation
#OS-07-029中mprotectMemory ProtectionHeap Allocation
Consider the following C program on x86_64 Linux.
01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <sys/mman.h>
04 #include <unistd.h>
05
06 int main() {
07
08 size_t pagesize = sysconf(_SC_PAGESIZE);
09
10 void *buffer = aligned_alloc(pagesize, pagesize);
11 if (!buffer) {
12 perror("Failed to allocate memory");
13 return EXIT_FAILURE;
14 }
15
16
17 if (mprotect(buffer, pagesize, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) {
18 perror("mprotect - error 1");
19 free(buffer);
20 return EXIT_FAILURE;
21 }
22
23 sprintf((char *)buffer, "This is a test.\n");
24
25 if (mprotect(buffer, pagesize, 0 ) == -1) {
26 perror("mprotect - error2");
27 free(buffer);
28 return EXIT_FAILURE;
29 }
30
31 printf("%s", (char *)buffer);
32 free(buffer);
33
34 return EXIT_SUCCESS;
35 }
Which of the following statement(s) are true?
📄 交大113
▤完整推導請見《WH 資工筆記 · 作業系統》Ch7 記憶體管理