Thread: Correct usage of malloc and free for 2D array

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    41

    Correct usage of malloc and free for 2D array

    I have a program that requires to create and delete a 2D array of variable size, hence the dynamic usage. However I wish to ask a simple question about the correct or recommended usage. For example, where should I reallocate the memory, should I simply free up the memory and use another allocation of memory i.e. memory allocation double etc should be done once...


    or should be done in the loop


    double **ptrBeadArrayOld = NULL;
    ptrBeadArrayOld = (double **)malloc(BeadTotal * sizeof(double *));
    for (i = 0; i< BeadTotal; i++)
    free_2d(ptrBeadArrayOld);

    or do I simply declare once?

    double **ptrBeadArrayOld = NULL;

    at the beginning of the program?? Thanks
    Last edited by disruptivetech; 10-20-2008 at 05:15 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Are you asking about whether you should determine the final size of the array and then allocate once, versus filling up the array and expanding when necessary?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 19
    Last Post: 12-17-2007, 02:57 AM
  2. Malloc - Free giving double free or corruption error
    By andrew.bolster in forum C Programming
    Replies: 2
    Last Post: 11-02-2007, 06:22 AM
  3. Replies: 12
    Last Post: 06-24-2005, 04:27 PM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Ask about free funtion using with malloc
    By ooosawaddee3 in forum C++ Programming
    Replies: 1
    Last Post: 05-12-2002, 04:43 PM