I'm trying to write a function which will free a dynamically allocated string by sending the address of the string (char*) to the function. (Sending char**)
I have tried doing it like this:
void dstring_delete(DString* stringToDelete)
{
// Precondition: stringToDelete is not NULL
assert(stringToDelete != NULL);
free(*stringToDelete);
Where DString is defined like this:
typedef char* DString;
The call to the function looks like this:
dstring_delete(&str1);
Where str1 is of type DString:
DString str1, str2;
I cant seem to figure out what is going wrong but this assert below the function call fails:
assert(str1 == NULL);
So my question is how I properly free the memory in this instance.
I have tried different arguments sent to the free function and also tried to find the same issues here.
CodePudding user response:
I assume that str1
is pointing to an allocated block that is to be freed and that the code sequence to free the block is like this:
dstring_delete(&str1);
assert(str1 == NULL);
OP's implementation of dstring_delete
seems to be as follows, but OP did not post the full function definition including the closing brace:
void dstring_delete(DString* stringToDelete)
{
// Precondition: stringToDelete is not NULL
assert(stringToDelete != NULL);
free(*stringToDelete);
}
It is not very clear from OP's question, but I think their code contains the following sequence, with str1
pointing to a previously allocated block to be freed:
dstring_delete(&str1);
assert(str1 == NULL);
OP wrote that the assert(str1 == NULL);
was failing. This is because dstring_delete
does not change the value of *stringToDelete
(which aliases the str1
variable) so *stringToDelete
(and the str1
variable) will still contain a non-null value on return from the function. However, the assert(str1 == NULL);
implies that it is expecting dstring_delete
to set the pointer value to NULL
. That is easily fixed by changing the function body of dstring_delete
to set the pointer to NULL
after freeing the allocated block:
void dstring_delete(DString* stringToDelete)
{
// Precondition: stringToDelete is not NULL
assert(stringToDelete != NULL);
free(*stringToDelete);
*stringToDelete = NULL;
}
Now, after the function call dstring_delete(&str1);
, str1
will be NULL
so the assert(str1 == NULL);
call will pass.
CodePudding user response:
The variable name of a string is itself a memory reference to the string; the type is char pointer and so the variable contains a pointer, which is a memory address. So when you call free() you only have to pass it the name of the variable.
(If you use the "&" you are passing the memory address where the string's memory address is located, and you only need the latter.)