使用fprintf输出__LINE__时出现分段错误

kre*_*ats 0 c printf

代码如下:

#include <stdio.h>

int main() {

    fprintf(stderr, "%s \n", __LINE__);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)
# gcc b.c
# ./a.out
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

__LINE__扩展为整数常量.使用%d打印出来:

fprintf(stderr, "%d \n", __LINE__);
Run Code Online (Sandbox Code Playgroud)

§6.10.8.1强制性宏(C11草案)

__LINE__当前源行的假定行号(在当前源文件中)(整数常量).


如果__LINE__溢出的宏int是一个问题,那么你可以将其转换uintmax_t并打印出来.这是最安全的方式,因为uintmax_t它是最大的整数类型.

#include <stdint.h>

fprintf(stderr, "%ju \n", (uintmax_t)__LINE__);
Run Code Online (Sandbox Code Playgroud)