Reputation: 221
I found an string buffer implemented in C here (https://sites.google.com/site/rickcreamer/Home/cc/c-implementation-of-stringbuffer-functionality). There is a function called dispose(), one of whose argument is an address of a pointer:
void dispose( SB **sb, int freeStrings ) {
if ( !sb || !*sb || !(*sb)->ptrList )
return; /* TODO: Decide if should abort here or take other action */
if ( freeStrings ) {
for ( int i = 0; i < (*sb)->count; ++i )
free( (*sb)->ptrList[ i ] );
}
free( (*sb)->ptrList );
free( *sb );
*sb = 0; /* Set value of pointer to zero */
}
I cannot understand why its first argument is the address of the pointer, rather than the pointer. What I would convert the function to is:
void dispose( SB *sb, int freeStrings ) {
if ( !sb || !sb->ptrList )
return; /* TODO: Decide if should abort here or take other action */
if ( freeStrings ) {
for ( int i = 0; i < sb->count; ++i )
free( sb->ptrList[ i ] );
}
free( sb->ptrList );
free( sb );
sb = 0; /* Set value of pointer to zero */
}
Do I miss something here?
Upvotes: 1
Views: 62
Reputation: 1
Pointer is variable type just like int, float
, etc... So, if you want to change it's value in a function, you have to pass a reference to it as an argument. That is why you have **sb
as parameter instead of *sb
.
Upvotes: 0
Reputation: 3836
In your example, sb = 0; /* Set value of pointer to zero */
actually sets the value of the local variable sb
to zero. That's the reason.
Upvotes: 0
Reputation: 53046
Because this prevents dangling pointers. Although it should be
*sb = NULL;
instead.
This way, after calling dispose(&sb)
you can check if sb == NULL
prior to dereferencing it and prevent dereferencing a pointer that has been freed.
And in your case, sb = 0
has no effect because you never use sb
after that.
Also, being freeStrings
a paramter I would argue that this is a flaw design. If the author wanted to have dual free()
behavior which is already bad, they should have had a freeStrings
member in the structure and then there would be a lot of control over whether the strings were owned by the structure or not.
Upvotes: 2