【问题标题】:seg fault error in accessing global pointer from function从函数访问全局指针时出现段错误错误
【发布时间】:2017-12-13 08:35:42
【问题描述】:

为什么当我在函数中为指针赋值时会出现分段错误。

source_1.c

int *p = NULL;

func(int **y)
{
    *y = (int *) malloc(sizeof(int));
    *y = 1;
}

int main()
{
    func(&p);
    printf("%d\n",*p);
}    

source_2.c

int *p = NULL;

func(int **y)
{
    *y = (int *) malloc(sizeof(int));
    *y = 1;
}

int main()
{ 
    int *t = p;
    func(&t);
    printf("%d\n",*t);
}        

指针定义和传递地址有什么问题?

【问题讨论】:

  • 看到这个问题:Pointer to pointer clarification
  • *y = 1; 将 1 分配给指针。当然是UB。你想要**y = 1吗?
  • 发布的代码存在一些问题。从他们开始,他们缺少stdio.h 和stdlib.h 的必要#include 语句
  • om C. 在调用任何堆分配函数(malloc、calloc、realloc)时 1) 始终检查 (!=NULL) 返回值以确保操作成功。 2) 返回类型为void*,因此可以分配给任何指针。强制转换只会使代码混乱,使其更难以理解、调试等。
  • 这一行:*y = 1; 覆盖了刚刚通过调用 malloc() 设置的指针,值为 1。代码现在有内存泄漏和 DE 引用该指针将尝试从地址 1 读取(这不是程序拥有的地址并且未正确对齐 int 值,也许您的意思是:*(*y) = 1;

标签: c pointers global


【解决方案1】:

您可以通过使用编译器警告标志找出指针操作中的问题。

在 Windows 和 Visual Studio IDE 中,使用内置调试器查看编码错误。

在 GCC 编译器的 linux 环境中,尝试使用此命令编译您的源代码(在我的情况下为 t.c)

gcc -Wall t.c -o t

gcc 产生这些警告

t.c:8:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 func(int **y)
 ^
t.c: In function ‘func’:
t.c:11:8: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
     *y = 1;
        ^
t.c:12:1: warning: control reaches end of non-void function [-Wreturn-type]
 }

很明显赋值*y = 1;是错误的。

感谢 Mark Benningfield 在using pointer to pointer 上介绍有用的链接

把你的代码改成这样可以解决你的问题

#include <stdio.h>


int *p = NULL;

void func(int **y)
{
    *y = malloc(sizeof(int));
    **y = 1;
}


int main()
{

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

}

首先对于不返回任何值的函数,使用 void 作为返回类型。 其次,如果我们尝试将指向函数的指针作为参数传递 例如func(int **y) 因为 y 可以保存指针的地址 我们必须用func (&amp;p) 调用它。 p 是一个整数指针。

最后建议不要将malloc()的结果转换为类似

(int *)malloc(sizeof(int))

cast the result of malloc?

【讨论】:

  • *y = (int *) malloc(sizeof(int)); 中不需要演员表。推荐*y = malloc(sizeof(int));,或者更好的*y = malloc(sizeof **y);
  • 你能解释一下他们之间的尊重是什么吗?或者只是介绍一个关于他们的链接?
  • 我只是在我的答案中复制粘贴 sagar 代码。但我认为 malloc() 返回一个 void * 更好地转换它。此外,此参考文献也没有将其放在示例中。 en.cppreference.com/w/c/memory/malloc
  • 见 stackoverflow.com/q/605845/2410359 您的 en.cppreference.com 参考是针对 C++ 而不是 C,就像这篇文章一样。
  • @chux 我的链接en.cppreference.com/w/c/memory/malloc 是关于 C 语言中的 malloc 虽然域名是 CPP。考虑链接 c/memory/malloc 的地址,并在示例中使用 stdlib,如果它是 C++ cstdio,则仅在 C 源代码中使用。感谢您考虑我的帖子,并提供一个关于我不太精通的投射指针的良好链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多