Set char pointer to NULL after using in a function

0

In C, I have a function in which I am getting a string as a parameter and then after using it, I want to destroy it, because I have to call it in an infinite loop and getting Process returned -1073741819 (0xC0000005) after 5 minutes.

Here's my function:

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

Passing argument as:

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.

c
pointers
null
malloc
asked on Stack Overflow Apr 22, 2019 by Usman Developer

2 Answers

6

This line

text[0] = '\0';

will dereference the pointer text but you have already

text = NULL;

so this will probably cause a segfault. You can

free(text);

but it is probably better to let the caller be responsible for that. This makes the function more useful for an argument that was not dynamically allocated, or that the caller wants to use again.

However your specific usage is

renderText("Hello There!");

and the string literal cannot be altered: it is read-only. So your function must not try to kill the argument passed.

answered on Stack Overflow Apr 22, 2019 by Weather Vane • edited Apr 22, 2019 by Weather Vane
2

Here

void renderText(char *text) { }

text is of char* type and after using it, to not to point text to any invalid memory location its always better to initialize with NULL which means it points to nothing. Hence this

text = NULL;

is correct only in this API as it doesn't reflect NULL assignment in calling function as text is locally created in this function. This

*text = NULL;

is not valid as *text is of char type while NULL is equivalent to (void*)0.

This

text[0] = '\0';

Works fine if error handling is according to above statement. For e.g

if(strlen(text) != 0) { /* something is there inside text */ }

answered on Stack Overflow Apr 22, 2019 by Achal • edited Apr 22, 2019 by Achal

User contributions licensed under CC BY-SA 3.0