Error in . / executable

Asked

Viewed 79 times

1

Good afternoon, I have this error when it comes to compiling the program:

* Error in `./executable': realloc(): invalid next size: 0x00000000012d12f0 * Aborted (recorded core image)

My program copies a file to a dynamically allocated array using realloc because I don’t know how big the rows and columns of the array are inside the file and then printed 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] = '\0';


    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;
}

1 answer

0

After the first realloc()

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

the new pointers in campo have an unspecified value. In particular the first time this instruction is executed (campo is null; i is zero) the realloc creates space for a pointer (campo[0]) but does not assign any value to it, leaving it with the garbage that existed in the assigned memory space.

Lower, next loop, you do

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

which is invalid as campo[0] has garbage.

Tip: uses calloc() which automatically initializes the assigned memory with zeros.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.