环境变量表
- 通过全局变量表指针environ访问进程所有环境变量
#include <stdio.h>
int main(void)
{
extern char **environ; // environ指向的是环境变量的首地址
char **pp;
for(pp = environ; *pp; ++pp)
printf("%s\n", *pp);
return 0;
}
- 通过main函数的第三个参数可以访问进程的环境变量
int main(int argc, char *argv[], char *envp[])
{
char **pp;
for(pp = envp; *pp; ++pp)
printf("%s\n", *pp);
return 0;
}
错误处理
- 在头文件
/usr/include/errno.h
中包含了对errno全局变量的外部声明 - 在头文件
/usr/include/asm-generic/errno-base.h
中包含各种错误号的宏定义
使用strerror()
函数了解错误原因
#include <stdio.h>
#include <stdlib.h>
#include <errno.h> // 使用errno需要引入errno.h
#include <string.h> // 使用strerror需要因为string.h
int main(void)
{
char *p = malloc(0xffffffffffffffffffff); // 这里分配内存空间超出内存总大小
if(p == NULL)
{
printf("errno = %d\n", errno); // 12
printf("malloc函数出错了,原因: %s\n", strerror(errno)); // malloc函数出错了,原因: Cannot allocate memory
return -1;
}
return 0;
}
使用perror()
函数了解错误原因
#include <stdio.h> // 使用perror需要引入stdio.h
#include <stdlib.h>
int main(void)
{
char *p = malloc(0xffffffffffffffffffff); // 这里分配内存空间超出内存总大小
if(p == NULL)
{
perror("malloc函数错误了,原因是"); // malloc函数错误了,原因是: Cannot allocate memory
return -1;
}
return 0;
}