No / Executable error

1

Good afternoon, I'm having this error when compiling the program:

  

Aborted

Aborted

My program copies from a file to a dynamically allocated array using realloc because I do not know the size of rows and columns of the array inside the file and then print it, the file has this format:

....*
*....
.....
.*...
.....

Follow the code below:

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

int main(void)
{
    char* nome = NULL;
    char ch;
    FILE *arq = NULL;
    size_t tam;
    int counter = 1, i = 0, j = 0, k = 0, l = 0, aux = 0;
    char** campo = NULL;

    getline(&nome, &tam, stdin);
    nome[strlen(nome) - 1] = '
....*
*....
.....
.*...
.....
'; arq = fopen(nome, "r"); if(arq == NULL) { printf("Erro, nao foi possivel abrir o arquivo\n"); } else { while( (ch=fgetc(arq))!= EOF) { campo = (char**) realloc(campo, (i + 1) * sizeof(char*)); while(ch != '\n') { campo[i] = (char*) realloc(campo[i], (i + 1) * sizeof(char)); campo[i][j] = ch; j++; aux = j; } j = 0; i++; } } for(k = 0; k < aux; k++) { for(l = 0; l < i; l++) { printf("%c ", campo[k][l]); } printf("\n"); } fclose(arq); return 0; }
    
asked by anonymous 09.08.2015 / 19:41

1 answer

0

After the first realloc()

    campo = (char**) realloc(campo, (i + 1) * sizeof(char*));

new pointers in campo have an unspecified value. Namely the first time this statement is executed ( campo is NULL; i is zero) realloc creates space for a pointer ( campo[0] ) but assigns it no value, leaving it with garbage which existed in the allocated memory space.

Further down, in the next loop, you do

        campo[i] = (char*) realloc(campo[i], (i + 1) * sizeof(char));
        //                         ^^^^^^^^

which is invalid, since campo[0] has garbage.

Tip: Use calloc() which automatically initializes the memory allocated with zeros.

    
09.08.2015 / 23:00