简体   繁体   中英

Reading Files with a double pointer and malloc

So, i am making the Game of Life of Conway.I want to read a file and save it in a double pointer and malloc it's memory but i am getting a crash in codeblocks. In the world i will put the dead and the living cells.

**world = (char **)malloc(grammes * sizeof(char));
for(i=0;i<grammes;i++)
    world[i]=(char *)malloc(stiles * sizeof(char));


for(i=0;i<grammes;i++)
{
    for(j=0;j<stiles;j++)
    {
        fscanf(fp,"%c",&world[i][j]);
    }
}

for(i=0;i<grammes;i++)
{
    for(j=0;j<stiles;j++)
    {
        printf("%c",world[i][j]);
    }
    printf("\n");
}
  1. By **world you access the actual value and not the address. You have to change it to world ( If you have already declared the variable)
  2. In the first line it should be sizeof(char*) because world is a pointer to an array of char*

Reason for crash is that world is double pointer and you should allocate memory for world first not for **world .

Replace below statement

  **world = (char **)malloc(grammes * sizeof(char));

with

 world = malloc(grammes * sizeof(char*)); //since world is double pointer it should be sizeof(char*)

Note : Typecasting of malloc is not required as suggested here Do I cast the result of malloc?

Well the thing is - you asked the question to misguide us not to help us to help you.

char ** world = malloc(..);

This is ok.

When you did this before char** world; and then you do this

**world = ...

Wrong. Because you have used a char to store the value of a pointer.

Well now see what you did, instead creating a chunk of memory which contains multiple char* you allocated for char then again used each of them to store the address of memory where char will be stored. Yes wrong it is

world = malloc(sizeof(char*) *grammes);

Better

world = malloc(sizeof *world * grammes);

And malloc 's return value should be checked and malloc returns a void* which can be implicitly converted to char* no need to cast the result.

world = malloc(sizeof *world * grammes);
if( world == NULL ){
    perror("malloc failed");
    exit(EXIT_FAILURE);
} 

Check the return value of fscanf also. You can check the man pages or standard to know their success value that hey return.


chux points out -

There are few more things but it is not sure if you will be engage in such details

malloc(sz) may return NULL if sz = 0 So saying malloc returns NULL means error is not perfectly correct or even if the sz is an overflown value then also it might return NULL .

Here it is better to write the check like this

if( world != NULL && grammes != 0){
   //Error.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM