Skip to content

Commit 94bf3f9

Browse files
committed
add stack overflow example
1 parent 8572c35 commit 94bf3f9

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

pmap/Makefile

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
PROGS=proc-addr-space
1+
PROGS=proc-addr-space stack-overflow
22

33
all: $(PROGS)
44

55
proc-addr-space: proc-addr-space.o
66
$(CC) -o $@ $^
77

8+
stack-overflow: stack-overflow.o
9+
$(CC) -o $@ $^
10+
811
clean:
912
rm -f *.o a.out $(PROGS)
1013

pmap/stack-overflow.c

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
* Demonstrate the behavior of process stack size limit.
3+
*
4+
* Compile with:
5+
* cc stack-overflow.c
6+
*
7+
* The first argument is the max recursion depth.
8+
*
9+
* Run with e.g.:
10+
* ulimit -s
11+
* ./a.out 8000
12+
*
13+
14+
*/
15+
16+
#define _XOPEN_SOURCE 700
17+
18+
#include <stdint.h>
19+
#include <stdio.h>
20+
#include <string.h>
21+
#include <unistd.h>
22+
#include <stdlib.h>
23+
#include <err.h>
24+
#include <signal.h>
25+
26+
void
27+
recurse(size_t n)
28+
{
29+
/* Intentionally unused variable to make the stack bigger */
30+
char foo[1024];
31+
32+
/* To silence the compiler warning */
33+
(void) foo;
34+
printf("%zu ", n);
35+
fflush(stdout);
36+
37+
if (n == 0) {
38+
printf("\n");
39+
return;
40+
}
41+
42+
recurse(--n);
43+
}
44+
45+
int
46+
main(int argc, char *argv[])
47+
{
48+
if (argc != 2)
49+
errx(1, "Usage: %s <iterations>", argv[0]);
50+
51+
/* Should have used strtoull(). */
52+
recurse(atoi(argv[1]));
53+
54+
return (0);
55+
}

0 commit comments

Comments
 (0)