1

Is there something wrong with the code below to allocate matrix 4X7?

char** imd = (char**)calloc(4, 7);


for (i=0; i < 4; i++)
    imd[i] = (char*)calloc(7, sizeof(char));

//then free allocated memory as below

for (i=0; i<4; i++)
     free(imd[i]);

free(imd);  
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
  • 1
    `4,7` --> `4, sizeof *imd` . The "row" is actually a pointer to where the row is going to be stored, you need to allocate space for 4 pointers – M.M Aug 11 '14 at 08:26
  • 1
    `char** imd = (char**)calloc(4, 7);` What's up with that? – dragosht Aug 11 '14 at 08:28
  • could you please modify it on my example? – user3928822 Aug 11 '14 at 08:29
  • `char **imd = calloc(4, sizeof *imd);` Using `sizeof` on the target is more robust than repeating type info, and [get rid of the bogus cast](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – M.M Aug 11 '14 at 08:42
  • I'd strongly suggest to actually allocate a true 2D array instead of what you are currently doing. What you have here is a pointer-based lookup table fragmented all over the heap. You also have pointless casts of the result from calloc. It seems likely that this code needs to rewritten from scratch, if you truly want to allocate a 2D matrix. – Lundin Aug 11 '14 at 08:45
  • Don't cast the return value of malloc/calloc! http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Klas Lindbäck Aug 11 '14 at 08:50

4 Answers4

1

First you need to allocate memory for 4 rows. Each row is a single pointer. But you are allocating memory for

char** imd = (char**)calloc(4, 7); // Bug

Where calloc(4, 7) have no meaning at all. so try the following fix-

char** imd = (char**)calloc(4, sizeof(char *)); // Fix


for (i=0; i < 4; i++)
imd[i] = (char*)calloc(7, sizeof(char));

//then free allocated memory as below

for (i=0; i<4; i++)
 free(imd[i]);

free(imd);  
Sathish
  • 3,740
  • 1
  • 17
  • 28
1
char** imd = (char**)calloc(4, 7);

to

char** imd = (char**)calloc(4, sizeof(char*));
chouaib
  • 2,763
  • 5
  • 20
  • 35
0

When you use calloc in that way, you're not asking for 4 char *s, each of which can point to an area of memory of size 7, you're asking for 4 elements, which are each 7 bytes.

What you want to do is:

char ** imd=(char **)calloc(4,sizeof(char *));

Which will give you a region of memory, zeroed, with room for four char *s.

The code you have right now might work, assuming sizeof(char *)<=7, but it shouldn't be considered correct, so there is "something wrong" with it.

0
#include <stdio.h>
#include <stdlib.h>

int main(void){
    char  (*imd)[7] = calloc(4, 7);//char imd[4][7];
    int i,j;

    for (i=0; i < 4; ++i){
        for(j=0; j < 7; ++j){
            imd[i][j] = i * 16 + j;
            printf("%02x ", (unsigned char)imd[i][j]);
        }
        printf("\n");
    }

    free(imd);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70