In: Computer Science
this is a test program foo that has a bug. Assume your machine has 4KB pages. Note that this code is runnable on a Linux machine.
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
struct foo {
int a; // 4-byte int
int b; // 4-byte int
};
int main (int argc, char * argv[]) {
int num = atoi(argv[1]); // convert program arg to integer
struct foo * a = mmap(NULL,
sizeof(struct foo) * num,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE,
-1,
0);
a[num].a = 100;
printf("Succeed\n");
}
[me@machine] ./foo 512
bash: “./test 512” terminated by signal SIGSEGV
[me@machine] ./foo 256
Succeed
Please find the correct program and added a comment for the reason of crash.
Cause for segment fault:
We are accessing the more than the allocated memory to assign the value of num.
More explanation:
Here the array index starts with 0-511. if we use 512
here it goes beyond the page size
256 is not issuing segmentation fault because we have page size
upto 4k(4096 bytes)
Error code:
a.[num]=100; //incorrect
Correct code:
a.[num-1]=100; //correct
Correct Program:
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
struct foo {
int a; // 4-byte int
int b; // 4-byte int
};
int main (int argc, char * argv[]) {
int num = atoi(argv[1]); // convert program arg to integer
struct foo * a = mmap(NULL,
sizeof(struct foo)*num,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE,
-1,
0);
//index starts with 0-511. if we use 512 here it goes
beyound the page size
//256 is not issuing segmentation fault because we have page size
upto 4k(4096 bytes)
a[num-1].a =
100;
printf("Succeed\n");
}
Sample Output:
USER>./a.out 256
Succeed
USER>./a.out 512
Succeed