not able to allocate memory with malloc...
Posted 11-12-2011 at 07:12 AM by mrajdeep
i have the following structures..
typedef struct
{
int cong_x_posx;
int cong_x_posy;
int vc;
}cong_x;
typedef struct
{
int cong_y_posx;
int cong_y_posy;
int vc;
}cong_y;
typedef struct {
int posX;
int posY;
int vc_count;
cong_x *cong_x1;
cong_y *cong_y1;
} grid;
following code works fine.....
grid **grid1;
grid1 = malloc(max_posx * sizeof(grid *));
if(grid1 == NULL)
{
printf("out of memory\n");
}
for(i = 0; i < max_posx; i++)
{
grid1[i] = malloc(max_posy * sizeof(grid));
if(grid1[i] == NULL)
{
printf("out of memory\n");
}
}
while trying to allocating memory to cong_x1 and cong_y1 as follow, it fails...
for(j=cury;j<=desy;j++)
{
printf("\n\n");
for(k=1;k<=curx;k++)
{
printf("\t");
}
for(i=curx;i<=desx;i++)
{
grid1[i][j].cong_x1 = malloc((desx-curx) * sizeof(*grid1[i][j].cong_x1));
grid1[i][j].cong_y1 = malloc((desy-cury) * sizeof(*grid1[i][j].cong_y1));
typedef struct
{
int cong_x_posx;
int cong_x_posy;
int vc;
}cong_x;
typedef struct
{
int cong_y_posx;
int cong_y_posy;
int vc;
}cong_y;
typedef struct {
int posX;
int posY;
int vc_count;
cong_x *cong_x1;
cong_y *cong_y1;
} grid;
following code works fine.....
grid **grid1;
grid1 = malloc(max_posx * sizeof(grid *));
if(grid1 == NULL)
{
printf("out of memory\n");
}
for(i = 0; i < max_posx; i++)
{
grid1[i] = malloc(max_posy * sizeof(grid));
if(grid1[i] == NULL)
{
printf("out of memory\n");
}
}
while trying to allocating memory to cong_x1 and cong_y1 as follow, it fails...
for(j=cury;j<=desy;j++)
{
printf("\n\n");
for(k=1;k<=curx;k++)
{
printf("\t");
}
for(i=curx;i<=desx;i++)
{
grid1[i][j].cong_x1 = malloc((desx-curx) * sizeof(*grid1[i][j].cong_x1));
grid1[i][j].cong_y1 = malloc((desy-cury) * sizeof(*grid1[i][j].cong_y1));
Total Comments 0