c - 在函数中使用后将 char 指针设置为 NULL

标签 c pointers null malloc

在 C 中, 我有一个函数,我在其中获取一个字符串作为参数,然后在使用它之后,我想销毁它,因为我必须在无限循环中调用它并且5 分钟后 进程返回 -1073741819 (0xC0000005)

这是我的函数:

void renderText(char *text) {
    //use it here and then destroy it.
    *text = NULL; //not working!
    text = NULL; //also not!
    text[0] = '\0'; //also not!
}

传递参数为:

renderText("Hello There!");

I can use a malloc() function to create a string and then can pass to the above function, but I have to call it infinite times so that is there any way to NULL it in the function as pointers are called by reference.

最佳答案

这一行

text[0] = '\0';

将取消引用指针 text 但你已经这样做了

text = NULL;

所以这可能会导致段错误。你可以

free(text);

但让调用者对此负责可能更好。这使得该函数对于不是动态分配的参数或调用者想要再次使用的参数更有用。

但是你的具体用法是

renderText("Hello There!");

并且字符串文字不能被更改:它是只读的。因此,您的函数不得尝试终止传递的参数。

关于c - 在函数中使用后将 char 指针设置为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55799191/

相关文章:

r - read.csv - 跳过具有不同列数的行

java - com.sun.istack.internal.Nullable 注释和 Guice

C - 在线程中的函数中传递字符串并返回它会导致不存在、不可打印的字符串?

c++ - 合并两个排序的链接列表

c++ - const 关键字在函数声明中的位置

C 指针值混合

python - 分配一个 pandas dataframe NULL=0, non-NULLvalue=1

c - 为什么这段代码的结果不一样?

调用一个 free() 包装器 : dereferencing type-punned pointer will break strict-aliasing rules

c - 哈佛 CS50 库,需要在 Mac OS X 上安装帮助