gpt4 book ai didi

c - 如何检查指针是否已被释放

转载 作者:行者123 更新时间:2023-12-02 01:48:07 25 4
gpt4 key购买 nike

我是 C 的初学者。下面是我的场景 - 我在 main 函数中创建了一个指针变量,它已传递给几个函数(在本例中为 2 个级别)。其中一项功能将其释放。现在我需要检查 Main 以查看指针是否被释放,这意味着我需要在 main() 中设置 &str 的值以指向 NULL。不确定我的方法是否正确。任何帮助将非常感激

void func2(char *str)   
{
free(str);
}

void func1(char *str)
{
func2(str);
}

int main()
{
char *str;
str=(char *) malloc(10);
func1(str);
if(str){ do something; } // if condition to check whether str is freed
}

最佳答案

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

func2(char **str)
{
free(*str); //free
*str = NULL; //Set to NULL
}

func1(char **str) //func1 receives as **
{
func2(str); //Pass pointer to func2()
}

int main()
{
char *str = NULL;
str=(char *) malloc(10);
func1(&str); //Pass Address of pointer to func1()

if(str) //Check for NULL
{
printf("\n Not - Freed...\n");
}
else
{
printf("\n Freed...\n");
}
return 0;
}

在 C 中都是按值传递的。我建议学习 http://www.cs.fsu.edu/~myers/cgs4406/notes/pointers.html为了理解这一点。

关于c - 如何检查指针是否已被释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com