【问题标题】:shows variable uninitialized when calling a function that uses malloc [duplicate]调用使用 malloc 的函数时显示变量未初始化 [重复]
【发布时间】:2022-01-30 21:14:47
【问题描述】:
# include<stdio.h>
# include<stdlib.h>
void fun(int *a)
{
  a = (int*)malloc(sizeof(int));
}
int main(void)
{
  int *p;
  fun(p);
  *p = 6;
  printf("%d\n",*p);
  free(p);
  return(0);
}

在 vs 代码中,这显示错误,因为 int *p 未初始化,并告诉我将变量 'p' 初始化为 NULL 以消除此警告。但是当我这样做时它编译但显示分段错误,可能是因为我将 6 分配给空地址,那么我该如何解决这个问题?

【问题讨论】:

  • 函数参数在 C 中通过值传递。所以a 是函数中的局部变量。设置它不会改变调用者的变量。有关更多详细信息和建议的修复,请参阅重复的帖子。
  • 侧节点:你可能想读这个:Do I cast the result of malloc?

标签: c function initialization pass-by-reference pass-by-value


【解决方案1】:

这个函数

void fun(int *a)
{
  a = (int*)malloc(sizeof(int));
}

更改自己的局部变量(参数)a。也就是该函数处理传递的指针p的值的副本

int *p;
fun(p);

指针p 保持不变且未初始化。

要使程序正确,您需要按以下方式更改代码

void fun(int **a)
{
  *a = (int*)malloc(sizeof(int));
}

//...

int *p;
fun( &p);

虽然在这种情况下,最好像这样声明和定义函数

int * fun( void )
{
   return malloc(sizeof(int));
}

//...

int *p = fun();

if ( p ) 
{
    *p = 6;
    printf("%d\n",*p);
}

free(p);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2014-11-04
    相关资源
    最近更新 更多