由printf导致的「Segmentation fault (core dumped)」

=Start=

缘由:

学习需要

正文:

参考解答:

如下的一段代码,测试了好多次,完全想不通为什么?只能说坑太多,踩不完……(也可能是因为对C语言理解不深)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char *a = NULL;
    printf("%s", a); // OK '(null)'
    printf("\n");
    // printf("%p", a); // OK '(nil)'
    // printf("\n");
    // printf("%s", NULL); // OK '(null)'
    // printf("%d", NULL); // OK 0
    // printf("%p", NULL); // OK '(nil)'
    // printf("\n");
    // printf("\n%s\n", a); // OK '(null)'
    // printf("\n%s", a); // OK
    // printf("%s\0", a); // OK '(null)'
    // printf("%sabc", a); // OK '(null)abc'
    // printf("%s\t", a); // OK '(null)    '
    // printf("%p\n", a); // OK '(nil)'
    // printf("%s\n", *a); // core dump (warning: format specifies type 'char *' but the argument has type 'char')
    printf("%s\n", a); // core dump (@linux but OK @Mac)
    // printf("%s\n", NULL); // core dump (@linux but OK @Mac)
    // printf("test:%s\n", a); // OK
    return 0;
}

printf的某些地方用的不当的话就会出现:编译时没有Warning,不易察觉,运行时低概率不定期coredump,简直让人崩溃。

参考链接:

Printf ubuntu Segmentation fault (core dumped) #可能是系统或架构的问题,重装了之后就好了……
https://stackoverflow.com/questions/13894194/printf-ubuntu-segmentation-fault-core-dumped

Execution of printf() and Segmentation Fault
https://stackoverflow.com/questions/9469790/execution-of-printf-and-segmentation-fault

为什么打印log(比如printf)会经常碰到core dump?
http://blog.csdn.net/stpeace/article/details/51165723
printf大坑等着很多人——一次core dump经历及定位过程(printf打印C++ string的时候忘了.c_st()转化)
http://blog.csdn.net/stpeace/article/details/50334915

Core dump与backtrace
http://blog.cuicc.com/blog/2012/09/17/core-dump-and-backtrace/

C语言中如何用printf打印指针类型变量?
https://stackoverflow.com/questions/1055959/print-the-address-a-pointer-contains-in-c
https://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-address
https://stackoverflow.com/questions/30354097/how-to-printf-a-memory-address-in-c

C语言结构体里的成员数组和指针
http://coolshell.cn/articles/11377.html

=END=

声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!
https://ixyzero.com/blog/archives/3335.html

《由printf导致的「Segmentation fault (core dumped)」》上有3条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注