C Quiz

Code help, language discussions, and software development advice.
Post Reply
Thermit
Registered User
Posts: 5
Joined: August 26th, 2004, 5:59 pm
Contact:

C Quiz

Post by Thermit »

Okay, let's see who knows their C...

The following simplified program compiles and links perfectly.


Code: Select all

int alloc_worked_main = 0;
int alloc_worked_sub = 0;

void main()
{
    char *ptr = NULL;

    set_mem ( ptr );

    if (ptr) alloc_worked_main = 1;

    printf ("main=%s,\nsub=%s\n", alloc_worked_main, alloc_worked_sub);
}


char * set_mem ( char *ptr )
{
     ptr = (char *) malloc ( 256 );

     if (ptr) alloc_worked = 1;
     
     return ptr;
}

It produces the following output...
main=0
sub=1

The pointer is NULL in main().

Why?
Thermit
Registered User
Posts: 5
Joined: August 26th, 2004, 5:59 pm
Contact:

Post by Thermit »

Okay, here's the answer...

This all boils down to pass-by-value vs. pass-by-reference.

The pointer isn't set in the main() because the pointer was passed to the function that allocates memory using pass-by-reference. This means that it wasn't the actual pointer from the main that was assigned the allocated memory, it was a copy. Once the memory allocation function set_mem() completes the address of the returned memory is lost.

To fix the problem call like this:

Code: Select all

set_mem ( & ptr );
And change the definition and code in set_mem() to accept a double pointer.

Then it all works as intended!
Post Reply