Thread: Question on free()

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Software engineer
    Join Date
    Aug 2005
    Location
    Oregon
    Posts
    283

    Question on free()

    I come from a C++ background where 'delete' was different if you're working with an array of memory. With free(), does it delete the array automatically?

    Code:
    #include <stdio.h>
    #include <stdlib.h>   
    #include <string.h>  
    #include "actor.h"
    #include "stack.h" 
    
    int main(void)
    {         
    	ASTACK stkActors;    
    	ACTOR PC, PC2, PC3;
    	ACTOR actTemp;
    
    	/* Initialize the actors */
    	Actor_Init(&PC, "Bob", 1);
    	Actor_Init(&PC2, "Bobby", 2);
    	Actor_Init(&PC3, "Other Bob", 3); 
    
    	/* Initialize the dynamic stack of 32 actors */
    	AStack_Init(&stkActors, 32);
    
    	/* Push actors into the stack. */
    	AStack_Push(&stkActors, &PC);
    	AStack_Push(&stkActors, &PC2);
    	AStack_Push(&stkActors, &PC3);
    
    	/* Pop away! */
    	AStack_Pop(&stkActors, &actTemp);
    	Actor_Show(&actTemp);
    
    	AStack_Pop(&stkActors, &actTemp);
    	Actor_Show(&actTemp);
    
    	AStack_Pop(&stkActors, &actTemp);
    	Actor_Show(&actTemp); 
    
    	/* Release the stack memory */
    	AStack_Release(&stkActors);
     
    	return 0;
    }
    (Just showing the code because it's beautiful).

    Actually, on AStack_Release(&stkActors), I call free() this way:

    Code:
    void AStack_Release(ASTACK *s)
    {
    	if (s->p_stck != NULL)
    		free(s->p_stck);
    	
    	s->p_stck = NULL;
    }
    Is that right? And I heard free() implicitly checks for null so the condition isn't necessary. Is this correct? Thanks.

    PS. Just a side note, how's this C coding style above that I developed for C coding? I think OO helped me to be clear more like myStructureType_DoSomething(&myStructure, ...).
    Last edited by dxfoo; 07-14-2010 at 10:31 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A question about performance and free()
    By The Physicist in forum C Programming
    Replies: 29
    Last Post: 05-26-2010, 10:44 AM
  2. Simple question about free()
    By fanoliv in forum C Programming
    Replies: 7
    Last Post: 06-16-2006, 11:14 AM
  3. question about free()
    By TalosChen in forum C Programming
    Replies: 5
    Last Post: 05-20-2006, 06:11 PM
  4. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM