小编jer*_*emy的帖子

为什么海湾合作委员会在教科书演习中没有瑕疵?

使用Adam Hoover的"使用C和Unix进行系统编程"学习C. 我从第4章遇到的问题让我很困惑.问题如下:

在下面的代码中,第一个printf()到达产生输出"14",但第二个printf()可能导致总线错误或分段错误.为什么?

书中的原始代码:

main()
{ 
  int *p;
  funct(p);
  printf("%d\n",*p);
}
funct(int *p2)
{
  p2=(int *)malloc(4);
  *p2=14;
  printf("%d\n",*p2);
}
Run Code Online (Sandbox Code Playgroud)

我稍加修改的"调试"(printf所有的东西)版本:

#include <stdio.h>
#include <stdlib.h>

void funct(int *p2);

int main(){
    int *p;
    printf("main p - address: %p\n", p);

    funct(p);
    printf("main p - address: %p\n", p);
    printf("main p value: %d\n", *p);
}  

void funct(int *p2){
    printf("funct (pre malloc) p2 - address: %p\n", p2);

    p2 = (int *)malloc(4);
    printf("funct (post malloc) p2 - address: %p\n", p2);

    *p2 = 14;
    printf("funct p2 value: …
Run Code Online (Sandbox Code Playgroud)

c gcc clang

1
推荐指数
1
解决办法
954
查看次数

标签 统计

c ×1

clang ×1

gcc ×1