errno 和 strerror函数

        今天写了一个很简单的代码,编译时没啥错误和警告(主要编译选项没开启警告),然后运行时居然 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值