Search code examples
cgccmallocfree

Program exits without any error when I try to free a 2d matrix in a struct


I create and fill my 2d array of unsigned char in my struct using parser of a file that contains numbers separated by spaces

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


struct imagem{
    unsigned char ** matrix;
    char* file_path;
    int height;
    int width;
    int max_cinza;
    int histograma[256];
    char* location;
};

struct imagem* lerImagem(char file_path[])
{

    struct imagem* imagem = malloc(sizeof(struct imagem)); 
    imagem->file_path = file_path;
    FILE* ptr;
    ptr = fopen(file_path, "r");
    
    if (NULL == ptr) {
        printf("A imagem não está no file_path selecionado \n");
        imagem->height = 0;
        return imagem;
    }
    int MAX_LEN = 10000;
    char buf[] = "";

    fgets(buf, MAX_LEN, ptr); 
    char width[10], height[10];

    fscanf(ptr, "%s %s", width, height);

    int int_largura = atoi(width);
    int int_altura = atoi(height);
    imagem->height = int_altura;
    imagem->width = int_largura;


    imagem->matrix = (unsigned char**) malloc(imagem->height * sizeof(unsigned char*)); 
    for (int i = 0; i < int_altura; i++) {
        imagem->matrix[i] = (unsigned char*) malloc(imagem->width* sizeof(unsigned char)); 
    }
    

    
    fscanf(ptr, "%u", &imagem->max_cinza);

    for(int row = 0; row < imagem->height; row++){
        for(int column = 0; column < imagem->width; column++){
            fscanf(ptr, "%u ", &(imagem->matrix[row][column]));
            }
        }   

    fclose(ptr);

    return imagem;
}

void freeImagem(struct imagem* imagem_input){
    
    printf("iniciando free de matrix");
    
    for(int i=0; i < imagem_input->height; i++){
            free(imagem_input->matrix[i]);
    }
    free(imagem_input->matrix);
    
    free(imagem_input);
}

I can compile and run that without any errors. The program seems to work randomly, as sometimes it frees properly and another times the program just stops without any explanation.


Solution

  • In the end, the problem was in file_path and location attributes, as I didn't used malloc to use them, this leads my program to broke randomly.