简体   繁体   中英

problem with allocation of a pointer to pointer of char

I wrote this code to copy the contents of file 'vetores' to a matrix of char but I think that there is a problem with the dynamic allocation. Somebody could help me?

void cpyarqvetores( char** arqvetores, FILE* varquivo);
void freearqvetores( char** arqvetores );

int main()
{
    FILE* varquivo;
    varquivo = fopen("vetores.txt", "r");
    char** arqvetores;
    arqvetores = (char**) malloc(10*sizeof(char*));
    cpyarqvetores( arqvetores, varquivo);
    printf("%s\n", *(arqvetores + 4));//try prints this line
    freearqvetores( arqvetores );
    fclose( varquivo );
    return 0;
}

//copy the contents of file 'vetores' to 'arqvetores'
void cpyarqvetores( char** arqvetores, FILE* varquivo){
    char aux[440];
    int strtam;
    int i, j;
    for( i = 0; i < 10; i++){
        fgets( aux, 440, varquivo);
        strtam = strlen( aux );
        *(arqvetores + i) = (char*) malloc(strtam*sizeof(char));
        if(*(arqvetores + i) == NULL)
            exit(-1);
        strcpy( *(arqvetores + i), aux);
    }
}

//free the allocated memory
void freearqvetores( char** arqvetores ){
    int i, j;
    int strtam;
    for( i = 0; i < 9; i++){
        strtam = strlen( *(arqvetores + i) );
        free(*(arqvetores + i));
    }
    free( arqvetores );
}

Here is the contents of file 'vetores':

1a 2a 3n 4n 2a 5a 6z 2z 1v 3a 11c 13e 3z 1e 14n 11n 2v 4a 3z 5a 6v 14e 2z 3a 11v
2a 2a 3z 4n 2a 5a 6z 8z 1v 3z 11c 13e 3z 2e 14n 11n 2v 4a 3z 2a 6v 14e 2z 3a 11v
3a 2a 3v 4n 2a 5a 6z 8a 1v 3a 11c 13e 3z 1e 11z 11n 2v 4a 3z 5a 6v 14e 2z 3a 11v
4a 2a 3v 4n 2a 5a 6z 8z 1v 3a 13c 13e 3z 1e 14n 11n 2v 3a 3z 5a 6v 14e 2z 7z 11v
5a 2a 4a 4n 2a 5a 6a 8z 1v 3a 11c 13e 3z 1e 14n 11n 2v 4a 3z 5a 6v 14e 2z 3a 11v
6a 2a 3z 4n 2a 5a 6z 8z 6v 3a 11c 13e 3n 1e 14n 11n 2v 5a 3z 5a 6v 14e 2z 3z 11v
7a 2a 3n 4n 2a 5a 6z 8z 1v 3a 11c 13e 3z 1e 14n 11n 2v 4a 3z 5a 6v 14e 2z 3a 11v
8a 2a 3a 4n 2a 5a 6z 8z 1v 3a 11c 13e 3z 1e 14n 11n 2v 4a 3z 5a 6v 14e 2z 3a 11v
9v 5a 6z 2n 1a 5z 6a 3z 3v 5a 13c 11a 3a 2e 13z 12e 2z 2a 3z 5a 6v 14e 2z 3z 11v
1n 4a 7v 5n 2z 4a 7z 8a 1v 8a 12z 11e 3v 1a 12z 14n 2z 2a 6v 5a 3v 14e 2z 4a 11z

You need to allocate an extra byte for each line to hold the terminating 0 byte:

    *(arqvetores + i) = (char*) malloc(strtam*sizeof(char));

should be

    *(arqvetores + i) = (char*) malloc((strtam+1)*sizeof(char));

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