简体   繁体   English

Linux上printf的分段错误

[英]segmentation fault with printf on linux

@Team, @球队,

While trying to print an integer value through printf i accidentally wrote the statement as 尝试通过printf打印整数值时,我不小心将语句写为

int x =10;
printf(x);

In linux i am getting a segmentation fault when tried to execute it. 在linux中,尝试执行分段错误。 Although its wrong but can some one please help me to know the reason for it. 虽然它是错误的,但是可以请一些人帮助我知道它的原因。

Strace says: Strace说:

mprotect(0x7f872fb26000, 4096, PROT_READ) = 0
munmap(0x7f872fb0b000, 99154)           = 0
--- SIGSEGV (Segmentation fault) @ 0 (0) ---
+++ killed by SIGSEGV (core dumped) +++

Tried searching in SO but to no success. 尝试在SO中搜索,但未成功。

First parameter for printf() is format string which is char * pointer. printf()第一个参数是格式字符串,它是char *指针。 So when you do printf(x) it takes x as char * and tries to access string stored at address 10 . 因此,当您执行printf(x) ,它将x作为char *并尝试访问存储在地址10字符串。 But its invalid so it gives segmentation fault. 但是它无效,因此会产生分割错误。

之所以会出现分段错误,是因为printf会将通过它的10解释为char * ,并试图从计算机地址10读取。在运行Linux的系统上,该地址无效并导致分段错误。

Use printf() in proper format. 以正确的格式使用printf()。 printf("%d",x). printf(“%d”,x)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM