在 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/