0
printf("\n enter your choice\n 1 to ask user for the size of game board\n 2 tp get input from a file\n");
scanf("%d",&choice);
if(choice==1)
{
    printf("\n enter number of rows and columns");
    scanf("%d%d",&row,&col);
    mat=(char**)malloc(row*sizeof(char));
    label=(char**)malloc(row*sizeof(char));
    for(i=0;i<row;i++)
    {
        mat[i]=(char*)malloc(col*sizeof(char));
        label[i]=(char*)malloc(col*sizeof(char));
    }

    for(i=0;i<row;i++)
    {

        for(j=0;j<col;j++)
        {
            temp=rand()%5;

            mat[i][j]=color_codes[temp];
            label[i][j]=' ';
        }

    }
}

this C Language statements is running fine on my visual studio IDE, but when i try to run this same statements on CODE BLOCKS IDE this thing suddenly crashes .Any kind of help will be highly appreciated

Jens
  • 69,818
  • 15
  • 125
  • 179

3 Answers3

2

There's an easy way to avoid this bug, where you multiply with the wrong value, when doing a malloc:

→ Always multiply with the sizeof the type of the array element, sizeof(*var).

 char **mat;

 mat = malloc (row * sizeof(*mat));

This way you'll never ever get the multiplications wrong again. Another advantage: Should you decide to change the type of mat to say, double, all you need to change is one place: its declaration.

And you shouldn't cast the malloc return value. It's been hashed to death on SO why.

Community
  • 1
  • 1
Jens
  • 69,818
  • 15
  • 125
  • 179
1

You are not allocating enough memory:

mat=(char**)malloc(row*sizeof(char));
label=(char**)malloc(row*sizeof(char));

Each item in the arrays is a pointer to char (char*), so you should multiply by sizeof(char*):

mat=(char**)malloc(row*sizeof(char*));
label=(char**)malloc(row*sizeof(char*));
nullptr
  • 11,008
  • 1
  • 23
  • 18
1

the two lines

mat=(char**)malloc(row*sizeof(char));
label=(char**)malloc(row*sizeof(char));

look not sane to me, you are trying to allocate an array of pointers to char but you specify only the size for a simple char. a pointer usually needs more that one byte.

so what you probably need is

mat=(char**)malloc(row*sizeof(char*));
label=(char**)malloc(row*sizeof(char*));

Note that it is not necessary to cats the result of malloc since in C a void* can be implicitly casted to any type.

So

mat=malloc(row*sizeof(char*));
label=malloc(row*sizeof(char*));

will work fine too.

A4L
  • 17,353
  • 6
  • 49
  • 70
  • And you **shouldn't cast** the malloc return value. It's been hashed to death on SO why. – Jens Jun 09 '13 at 15:01