C语言程序在内存中布局图
High Address +-------------------------+
↑ | Command-line arguments |
| | & environment variables |
| +-------------------------+
| | Stack area |
| | | |
| | | |
| | ↓ |
| +-------------------------+
| | ↑ |
| | | |
| | | |
| | Heap area |
| +-------------------------+
| | uninitialized data | // BSS (Block Started by Symbol) Segment
| +-------------------------+
| | initialized data | // Data Segment
| +-------------------------+
| | code/text segment |
Low Address +-------------------------+
main函数栈帧图
+---------------------+
| Null-terminated |
| env var strings |<------+
+---------------------+ |
| Null-terminated | |
| cmdline arg strings |<--+ |
+---------------------+ | |
| unused | | |
+---------------------+ | |
| envp[n] == NULL | | |
+---------------------+ | |
| envp[n-1] | | |
+---------------------+ | |
| ... | | |
+---------------------+ | |
+------>| envp[0] |-------+
| +---------------------+ |
| | argv[argc] == NULL | |
| +---------------------+ |
| | argv[argc-1] | |
| +---------------------+ |
| | ... | |
| +---------------------+ |
| +-->| argv[0] |---+
| | +---------------------+
| | | Linker vars |
| | +---------------------+
+-------| envp |
| +---------------------+
+---| argv |
+---------------------+
| argc |
+---------------------+
| Stack frame for |
| main function |
+---------------------+
输出所有命令行参数:
#include <stdio.h>
int
main(int argc, char *argv[])
{
int i;
/* echo all command-line args */
// for (i = 0; argv[i] != NULL; i++) {
for (i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, argv[i]);
}
/* `exit(0);` is the same as `return(0);` from the `main` function. */
return 0;
}
APUE 摘录:Returning an integer value from the main
function is equivalent to calling exit
with the same value. Thus exit(0);
is the same as return(0);
from the main
function.
APUE 摘录:We are guaranteed by both ISO C and POSIX.1 that argv[argc]
is a null pointer. This lets us alternatively code the argument-processing loop as for (i = 0; argv[i] != NULL; i++)
.