首页 > C语言printf的使用问题

C语言printf的使用问题

在写C测试指针的使用的时候,使用printf函数输出,出现了下面的情况,关于指针的问题我已经清楚,希望谁能给我说清楚输出的问题

首先是有下面这样的代码


#include<stdio.h>
int main()
{
    int *p;
    p = (int*)malloc(sizeof(int));
    *p=3;
    printf("%d, ", p);
    printf("%d, ", *p);

    free(p);
    printf("%d, ", p);
    printf("%d, ", *p);

    p = NULL;
    printf("%d, ", p);
    printf("%d\n", *p);
    return 0;
}

输出结果是:

Segmentation fault (core dumped)

但是如果代码是这样的,就是在每个printf中多加了\n,就得到了想要的输出结果

#include<stdio.h>
int main()
{
    int *p;
    p = (int*)malloc(sizeof(int));
    *p=3;
    printf("%d\n", p);
    printf("%d\n", *p);

    free(p);
    printf("%d\n", p);
    printf("%d\n", *p);

    p = NULL;
    printf("%d\n", p);
    printf("%d\n", *p);
    return 0;
}

输出结果是:

29540368
3
29540368
0
0
Segmentation fault (core dumped)

这是为什么?


猜测: printf 遇到 \n 时,调用了 flush 刷新输出缓存,直接输出到屏幕了,而 , 不会引起 printf 调用 flush

free 只是将 p 指向的内存空间作了一个 空闲 标记,不释放 p 本身,所以访问 p没问题,但是访问 *p 的结果是未定义的。一直到最后一行,访问空指针,程序就段错误了。


弄错了,编辑掉


apue, 看一下 什么叫 标准输出的 的行缓存.

【热门文章】
【热门文章】