Dynamic two dimensional array free problem

This is a discussion on Dynamic two dimensional array free problem within the C Programming forums, part of the General Programming Boards category; Hi My program is crashing while I am trying to free to memory in 2-D array. The code is: Code: ...

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

    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,185
    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
    75
    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
    21,721
    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++?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

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

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

    Thanks

  7. #7
    Registered User
    Join Date
    Jun 2010
    Posts
    75
    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
    21,721
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Jun 2010
    Posts
    75
    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 10:54 AM. Reason: update

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,721
    Yes.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Jun 2010
    Posts
    75
    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 11:04 AM. Reason: change

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,721
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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,832
    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
    21,721
    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 11:30 AM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Jun 2010
    Posts
    75
    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, 07:02 AM
  3. problem on dynamic array
    By Roy01 in forum C++ Programming
    Replies: 3
    Last Post: 12-09-2006, 07: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21