今天写了一个很简单的代码,编译时没啥错误和警告(主要编译选项没开启警告),然后运行时居然 segmentation fault,把我给看傻了,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd = open("readme", O_RDWR);
if(fd < 0)
{
printf("open fail: %s\n", strerror(errno));
return fd;
}
return 0;
}
代码简单吧,就把 errno 对应的字符串打印出来,结果就 Segmentation fault 了,搞得我以为用法不对呢,我还去 man 了一个 strerror() 函数的用法:
用 %s 打印 char * 类型,是对的啊,怎么会这样呢?搞得我还去看了源码,顺便学习了一下 errno,原因后面再讲到。先看一下函数 strerror() 的源码:
/* Copyright (C) 1991-2022 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
L