Thread: Malloc/Free

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    8

    Question Malloc/Free

    I am a relatively new coder, so this may be a silly question but I've as yet to find an adequate answer, or any answer at all for that matter.

    Why use malloc/free? In what particular situations should they be used? My only guess, so far, is to use them to conserve memory. So...if one were to save large amounts of data in a variable, say a struct or very large array, instead of initializing the struct or array in its full size, then add/remove it from memory as you need it? Does the variable need to be defined as a pointer or typical varible?

    Example:

    Code:
    {
      int *p;
    
      /* some kind of code */
    
      p = malloc(999999); /* arbitrary number for arguments sake */
    
      /* error check then do something with int array */
    
      free(p);
      p = 0; /* or NULL */
    
      /* rest of code */
    }
    I also read that it was necessary for proper use of nested arrays or linked structs but with no explanation why. I'm not 100% I understand how they work anyways, or why you'd use them. My understanding of a linked list is thus:

    Code:
    struct linkedlist {
      int x;
      struct linkedlist link;
    };
    I think I must be missing the point of using a linked list...

    Thanks in advance,

    Rob
    Last edited by JupiterV2; 09-08-2006 at 09:36 AM.

  2. #2
    Jaguar
    Join Date
    Sep 2006
    Posts
    12
    Hey,

    Size is not known most of the time. Then how can you allocate the maximum size. If you use a very large number, you are eating the memory.

    Read more about linked lists. They are smarter when you are using queues, stacks, trees etc.

    Good Luck

    Jag

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > Why use malloc/free? In what particular situations should they be used?
    You use them when you don't know at compile time how many things you need.

    Eg.
    "How many integers do you want?"
    You read the answer, then allocate that amount.

    > I think I must be missing the point of using a linked list
    There are many different data structures, which are more useful than arrays, depending on what you want to do.
    A linked list for example can grow from either end with the same ease. Appending to the end of an array is very easy, but appending to the start requires an awful lot of moving around to make space for the new data.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Aug 2006
    Posts
    11
    malloc is used to reserve some portion of memory
    This memory will be referenced as a pointer

    As already said, this is useful when you don't know explicitely how much memory you would need when you are coding your program.

    When you deal with pointers, you will end up finally using malloc to reserve just exactly the amount of memory you need. And not only that, you can even resize the memory using realloc , something, that, if you have reserved memory statically ( char array[100] ) you can't do.

    Other idea, if you reserved memory statically (char array[100000]) , you program is taking that memory even if it's not using it at all. This program requires all that memory.
    but using malloc, calloc, realloc , free (all the family) , you can be more moderated in your resource consumption, freeing that memory your program is not using at htat moment, making your program more friendly with other programs in the system.

    --------------------------------------------
    http://www.uberum.com

  5. #5
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    Code:
    #include <stdio.h>
    int main()
    {
        int size;
        printf("How many numbers do you want to enter: ");
        scanf("%d", &size);
        
       /* make array of that size ... */
    }
    Now how do you make a static array of size size? This is what _alloc functions are for.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by jafet
    Now how do you make a static array of size size?
    You use C99, duh!

    Code:
    #include<stdio>
    
    int main( void )
    {
        int siz = 0;
        printf( "Enter array size: " );
        fflush( stdout );
        while( scanf( "%d", &siz ) != 1 && siz < 1 );
    
        int array[ siz ];
        size_t ohgodmakeitstop;
    
        for( ohgodmakeitstop = 0; ohgodmakeitstop < siz; ohgodmakeitstop++ )
        {
            ...do stuff...
        }
    
        return 0;
    }
    C99 is ugl...good...it's good. Much nicer looking code can be now written.

    Ok, I can't go on here... It's crap. It's ugly putrid crap!


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. New/delete vs malloc/free
    By KBriggs in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2009, 03:08 PM
  2. malloc/free help
    By stan4d2012 in forum C Programming
    Replies: 3
    Last Post: 04-13-2009, 07:04 PM
  3. redirect malloc/free
    By pheres in forum C Programming
    Replies: 0
    Last Post: 03-21-2009, 03:28 AM
  4. Tracking memory in malloc/free.
    By matsp in forum C Programming
    Replies: 10
    Last Post: 01-07-2009, 05:16 AM
  5. malloc/free mark
    By yosoyvenezolano in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 10:45 AM