+ Reply to Thread
Page 1 of 3
1 2 3 LastLast
Results 1 to 10 of 27

Thread: Dynamic Arrays: Using malloc() and realloc()

  1. #1
    Code Warrior Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest's Avatar
    Join Date
    Sep 2009
    Location
    United States
    Age
    16
    Posts
    2,664
    Blog Entries
    3

    Dynamic Arrays: Using malloc() and realloc()

    Note: This tutorial uses pointers pretty heavily. If don't understand pointers, please read this tutorial before you go on.

    This has been bugging me for a little while, but I figured it out. I will share my knowledge to the rest of the world! If you need to take data from the user that could be any length, you could define a really big array like so:
    Code:
    int array[100000];
    There are several problems with this. No matter how big the array is, the user could still have more input. If the user doesn't have that much input, you have wasted memory.

    When you are using malloc(), realloc() and free() you need the following header file:
    Code:
    #include <stdlib.h>
    First, I will show you how to allocate memory for a pointer. You can declare a pointer like so:
    Code:
    int *pointer;
    The pointer can point to any location at first. You should always make it point to something or you can allocate some memory that your pointer will point to. To do this, you need to use the malloc() function. Use it like so:
    Code:
    pointer=malloc(2*sizeof(int));
    malloc() returns a void pointer and takes an argument of how many bytes to allocate. Because pointer points to an integer, we use the 2*sizeof(int). Using malloc like the above is similar to doing this:
    Code:
    int array[2];
    Error checking:
    If the operating system can't allocate more memory for your program, malloc will fail and return a NULL value. It's always a good idea to make sure malloc is successful:
    Code:
    pointer=malloc(1*sizeof(*pointer));
    if (pointer==NULL) {
        printf("Error allocating memory!\n"); //print an error message
        return 1; //return with failure
    }
    Now I will show you how to use realloc(). You use realloc after you have used malloc to give a pointer more or less memory. Let's say you want to give a pointer 5 integers of memory. The code should look like this:
    Code:
    int *temp = realloc(pointer, 5*sizeof(int));
    if ( temp != NULL ) //realloc was successful
    {
       pointer = temp;
    }
    else //there was an error
    {
       free(pointer);
       printf("Error allocating memory!\n");
       return 1;
    }
    This is just like malloc, except realloc takes two arguments. The first argument is the pointer you want to copy the data from. The above code copies pointer to temp, then copies temp back to pointer if everything goes correctly. You may have noticed a new function though, and that is free().

    Free is used to free the memory you have allocated with malloc or realloc. All memory that you allocate should be freed when you are done using it. Free takes a pointer as an argument like so:
    Code:
    free(pointer);
    Here is an example program that makes use of a dynamic array. Everything you need to know is in the comments.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    /* This program takes input and outputs everything backwards */
    
    int main()
    {
        int *data,*temp;
        data=malloc(sizeof(int));
        int c; /* c is the current character */
        int i; /* i is the counter */
        for (i=0;;i++) {
            c=getchar(); /* put input character into c */
            if (c==EOF) /* break from the loop on end of file */
                break;
            data[i]=c; /* put the character into the data array */
            temp=realloc(data,(i+2)*sizeof(int)); /* give the pointer some memory */
            if ( temp != NULL ) {
                data=temp;
            } else {
                free(data);
                printf("Error allocating memory!\n");
                return 1;
            }    
        }
        /* Output data backwards one character at a time */
        for (i--;i>=0;i--)
        putchar(data[i]);
        /* Free the pointer */
        free(data);
        /* Return success */
        return 0;
    }
    So that's it. Any suggestions for improvement are welcome. +Reputation is very much appreciated.
    Last edited by Guest; 03-15-2010 at 11:39 PM. Reason: Improved wording
    Code:
     / ___|_   _  ___  ___| |_ 
    | |  _| | | |/ _ \/ __| __|
    | |_| | |_| |  __/\__ \ |_ 
     \____|\__,_|\___||___/\__|

  2. #2
    Super Moderator WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther's Avatar
    Join Date
    Jul 2006
    Age
    36
    Posts
    11,702
    Blog Entries
    57

    Re: Dynamic Arrays: Using malloc() and realloc()

    Nicely done. +rep
    CodeCall Blog | CodeCall Wiki | Shareware
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

  3. #3
    Code Warrior marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89's Avatar
    Join Date
    Jul 2008
    Location
    Somewhere that is shorter to write than "In the gloomy shadows of my personal namespace"
    Posts
    10,164
    Blog Entries
    2

    Re: Dynamic Arrays: Using malloc() and realloc()

    Good work, +rep, but I would just like to point out one thing:

    You say that
    This pointer currently doesn't point to anything, it is empty. You can make it point to something or you can give the pointer some memory.
    When you allocate memory, you make the pointer point to the start of the newly allocated memory block. A pointer does always points to something (or has the value NULL). You do not "give the pointer memory", you allocate memory for the program and use the pointer to know where that memory is.

    Except from that, good tutorial, and it deserves +rep

  4. #4
    Guru debtboy is just really nice debtboy is just really nice debtboy is just really nice debtboy is just really nice debtboy is just really nice debtboy's Avatar
    Join Date
    Aug 2009
    Location
    I'm in the... Black Lodge
    Posts
    908

    Re: Dynamic Arrays: Using malloc() and realloc()

    Good Tutorial +rep
    The owls are not what they seem...

  5. #5
    Code Warrior Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest's Avatar
    Join Date
    Sep 2009
    Location
    United States
    Age
    16
    Posts
    2,664
    Blog Entries
    3

    Re: Dynamic Arrays: Using malloc() and realloc()

    Thanks everyone! I appreciate the feedback.
    @marwex89: I probably should have paid more attention to wording. It's changed now.
    Edit: I just realized this is my 100th post!
    Code:
     / ___|_   _  ___  ___| |_ 
    | |  _| | | |/ _ \/ __| __|
    | |_| | |_| |  __/\__ \ |_ 
     \____|\__,_|\___||___/\__|

  6. #6
    Code Warrior marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89's Avatar
    Join Date
    Jul 2008
    Location
    Somewhere that is shorter to write than "In the gloomy shadows of my personal namespace"
    Posts
    10,164
    Blog Entries
    2

    Re: Dynamic Arrays: Using malloc() and realloc()

    I know I'm picking on you now, but I'd further edit that sentence(s)

    The pointer has the NULL value at first. You can make it point to something or you can allocate some memory for it. To do this, you need to use the malloc() function.
    1. The contents of a pointer is not guaranteed to be NULL at declarations. It is probably pointing to some random location. You are usually advised to specifically initialize it to NULL like this:

    Code:
    int* pointer = NULL;
    2. You're still not allocating memory for the pointer, you are allocating memory for your program, to hold data. The pointer just points to it.

    I'm sorry that I'm picking on you like this, but I guess it's kinda important to get this right. And you asked for it:
    Any suggestions for improvement are welcome.


    Congrats on 100!

  7. #7
    Code Warrior Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest is a name known to all Guest's Avatar
    Join Date
    Sep 2009
    Location
    United States
    Age
    16
    Posts
    2,664
    Blog Entries
    3

    Re: Dynamic Arrays: Using malloc() and realloc()

    I think i got it now. My C book that I bought was kind of an intro to C. It didn't explain things in such great detail. I don't understand all the technical little things yet.
    Code:
     / ___|_   _  ___  ___| |_ 
    | |  _| | | |/ _ \/ __| __|
    | |_| | |_| |  __/\__ \ |_ 
     \____|\__,_|\___||___/\__|

  8. #8
    Code Warrior marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89 is a glorious beacon of light marwex89's Avatar
    Join Date
    Jul 2008
    Location
    Somewhere that is shorter to write than "In the gloomy shadows of my personal namespace"
    Posts
    10,164
    Blog Entries
    2

    Re: Dynamic Arrays: Using malloc() and realloc()

    It's OK, I'm just picky

  9. #9
    Administrator Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan's Avatar
    Join Date
    Nov 2005
    Location
    Hendersonville, NC
    Posts
    24,556
    Blog Entries
    97

    Re: Dynamic Arrays: Using malloc() and realloc()

    Well written and well done. +rep

  10. #10
    Co-Administrator John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John's Avatar
    Join Date
    Jul 2006
    Age
    21
    Posts
    5,885
    Blog Entries
    25

    Re: Dynamic Arrays: Using malloc() and realloc()

    I finally had time to read through and think about this. Very nice.

    From what I understand, you reallocate memory for every input character? It might be more efficient to initially allocate an array of a certain size, then once the array becomes most of the way filled, reallocate memory (and double the size of the array). Granted some memory could be waisted, but if I can recall from my data structures class - this is how C++/Java vectors work, and tends to be most efficient. Maybe someone can verify this.

+ Reply to Thread
Page 1 of 3
1 2 3 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Similar Threads

  1. Replies: 5
    Last Post: 10-22-2008, 08:40 PM

Bookmarks

Bookmarks

     
        Algorithms and Data Structures

        Java tutorials

        Algorithms Forum

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts