BugRepairMan BugRepairMan - 10 months ago 41
C Question

Why does the argument use an address of a pointer here?

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download