Thread: Dynamic two dimensional array free problem

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    103

    Dynamic two dimensional array free problem

    Hi

    My program is crashing while I am trying to free to memory in 2-D array.

    The code is:

    Code:
     int main()
    {
    	char **temp;
    	int row = 5;
    	int col = 10; 
    
    	temp = (char **) malloc ( sizeof(char) * row);
    
    	for (int i = 0; i < row ; i++) { 
    	temp[i] = (char *) malloc ( sizeof(char) * col);
    	memcpy(temp[i],"Copying Test",20);
    	}
    	
    	for (int i = 0; i < row ; i++) { 
    		cout<<temp[i]<<endl;
    	}
    
                  for (int i = 0; i < row ; i++)  
                	free((void *)temp[i]);
    
    }

    Can anybody help me in this.

    Thanks

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    temp = (char **) malloc ( sizeof(char*) * row);

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Well, there's the little matter that you're exceeding array bounds.

    You correctly assign 5 rows ... then create 5 10 character strings...

    But then you memcopy 20 characters into each string.

    Most likely it's crashing when you first access it with the C++ cout function. Because you are exceeding array bounds with every string.

  4. #4
    Registered User
    Join Date
    Jun 2010
    Posts
    103
    Thanks for reply.... Now its not crashing.

    One more question.

    How can memset each temp[i] ?
    I am using :

    memset(temp[i],'\0',10);
    but it is not working and crashing.

    Thanks

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    A few things to note:
    • You don't have to cast the return value of malloc.
    • You don't have to cast the pointer to void* to use free.
    • Besides using free for each inner dynamic array, you should also use it for the outer dynamic array.
    • sizeof(char) == 1 is always true, so either omit it, or use the idiom:
      Code:
      temp = malloc(sizeof(*temp) * row);
    • If each of the inner arrays will always be of the same size, then this method is unnecessarily expensive.

    For the last point, an alternative is:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)
    {
        const char str[] = "Copying Test";
        int num_rows = 5;
        int num_cols = sizeof(str);
        /* Assume that malloc does not return a null pointer */
        char *data = malloc(sizeof(*data) * num_rows * num_cols);
        char **temp = malloc(sizeof(*temp) * num_rows);
        int i;
        for (i = 0; i < num_rows; ++i)
        {
            temp[i] = &data[i * num_cols];
            memcpy(temp[i], str, num_cols);
        }
    
        for (i = 0; i < num_rows; ++i)
        {
            printf("%s\n", temp[i]);
        }
    
        free(temp);
        free(data);
        return 0;
    }
    Incidentally, considering that you use cout: is this C or C++?
    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

  6. #6
    Registered User
    Join Date
    Jun 2010
    Posts
    103
    Thanks Laser....

    But how can I memset it to '\0' or space when needed.

    Thanks

  7. #7
    Registered User
    Join Date
    Jun 2010
    Posts
    103
    One more thing....

    If I don't cast malloc..it is giving error. No idea why.
    I am using MS Visual studio.


    Thanks

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by nickman
    But how can I memset it to '\0' or space when needed.
    If you are using the option I suggested, then you can just memset the entire data array to hold '\0'. The trick is that temp is then used as if it were a 2D array, but of course it is just a pointer to a pointer.

    Quote Originally Posted by nickman
    If I don't cast malloc..it is giving error. No idea why.
    I am using MS Visual studio.
    Because you are compiling as C++. Compile as C by changing the .cpp extension to .c and changing the project configuration.
    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

  9. #9
    Registered User
    Join Date
    Jun 2010
    Posts
    103
    Hi

    Could you please help me with syntax to use to memset here...It will be very helpful.

    I am using this. Is it OK..

    memset(data,'\0',sizeof((*data) * num_rows * num_cols));
    Thanks
    Last edited by nickman; 01-13-2011 at 11:54 AM. Reason: update

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes.
    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

  11. #11
    Registered User
    Join Date
    Jun 2010
    Posts
    103
    Thanks Laser.....

    I have one more curious question.

    What's the difference between your way and my way. It seems that both are same.
    How is my way expensive.?

    Could you please elaborate more on this.
    And also I should memset in my earlier code?


    Thanks
    Last edited by nickman; 01-13-2011 at 12:04 PM. Reason: change

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by nickman
    What's the difference between your way and my way. It seems that both are same.
    How is my way expensive.?
    Compare the number of calls to malloc and free. However, the method you originally used tends to be more feasible when you want "jagged" 2D arrays, i.e., where each inner array is of a different size.

    Quote Originally Posted by nickman
    And also I should memset in my earlier code?
    It depends on what you are trying to do. As long as you give variables an initial value before you use them, you're on the right track.
    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

  13. #13
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Quote Originally Posted by nickman View Post
    Hi

    Could you please help me with syntax to use to memset here...It will be very helpful.

    I am using this. Is it OK..

    memset(data,'\0',sizeof((*data) * num_rows * num_cols));

    Thanks
    I don't think so. You can't do math inside sizeof().

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by nonoob
    I don't think so. You can't do math inside sizeof().
    Ooh, good catch (though technically wrong too: you can do math inside the sizeof expression, though it does not actually get evaluated). Too many parentheses.

    nickman, I suggest that instead of immediately reaching for the post button, compile and attempt to run your code first. Test your hypotheses and ask to confirm if they tally, or for an explanation on why they don't tally.
    Last edited by laserlight; 01-13-2011 at 12:30 PM.
    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

  15. #15
    Registered User
    Join Date
    Jun 2010
    Posts
    103
    Thanks to all.....

    My problem is solved.

    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamic array and structure problem
    By bluetxxth in forum C Programming
    Replies: 3
    Last Post: 04-13-2010, 06:56 AM
  2. Problem within multi dimensional array
    By lolguy in forum C Programming
    Replies: 5
    Last Post: 12-26-2008, 08:02 AM
  3. problem on dynamic array
    By Roy01 in forum C++ Programming
    Replies: 3
    Last Post: 12-09-2006, 08:04 AM
  4. simple array of char array problem
    By cloudy in forum C++ Programming
    Replies: 5
    Last Post: 09-10-2006, 12:04 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM