1
votes

Basically I'm trying to code a reader for JPEG files (using libjpeg) but I have a segfault, and I wanted to know if someone could see where is my error ? I'm sure it comes from the malloc but I don't know. I tried to put some debug by putting some printf but absolutely NONE of them appear, wtf ?

Thanks for your help mates...

main.c :

#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
#include "fonctions.h"


int main (int argc, char** argv){


    int *H;
    int *W;
    int *C;
    printf("COUCOUCOUCOUCOU");
    FILE *fichier = NULL;
    char car;

    fichier = fopen("cara.jpg", "r");

    if (fichier == NULL)
        printf("Probleme lecture");


    lire(fichier, H, W, C);

    fclose(fichier);
    return 0;
}   

lire.c :

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <jpeglib.h>
#include <jerror.h>

unsigned char** lire (FILE* file, int *H, int *W, int *C){

struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;

int n = 0;
unsigned char** buffer;

printf("SHITSHITSHITSHIT\n");
fflush(stdout);
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo); // Initialisation de la structure

jpeg_stdio_src(&cinfo,file);  // file est de type FILE * (descripteur de fichier
                              // sur le fichier jpega decompresser)
jpeg_read_header(&cinfo,TRUE);// lecture des infos sur l'image jpeg


jpeg_start_decompress(&cinfo);// lancement du processus de decompression


*H = cinfo.output_height;
*W = cinfo.output_width;
*C = cinfo.output_components;

buffer=(unsigned char **)malloc( (*H) *sizeof(unsigned char*) );

while (n < *H)
 {
    buffer[n] = (unsigned char*) malloc( (*W) * (*C) *sizeof(unsigned char *) );
        printf("DEBUG\n");
    fflush(stdout);
     jpeg_read_scanlines(&cinfo,buffer+n,1); // lecture des n lignes suivantes de l'image
                                          // dans le buffer (de type unsigned char *)
     n++;
}

jpeg_finish_decompress(&cinfo);

jpeg_destroy_decompress(&cinfo);

return buffer;
}

i compile with :

gcc -c -I/usr/local/include *.c
gcc *.o -o programme -ljpeg
1
Try flushing stdout so that your (buffered) debug statements appear before the program crashes, e.g. printf("COUCOUCOUCOUCOU"); fflush(stdout); - mhawke
ok so i put a "fflush(stdout)" on the beginning of the code ? - Henley n
And where is the lire function ? - Jabberwocky
OMG sry ! lire function is "read" ! i translated it but it's bc "lire" means "read" in french :) (i edited) - Henley n
Did you realise that you have posted the same code twice? i.e. main.c and lire.c are identical. I think that the code from lire.c is missing in your question. - mhawke

1 Answers

2
votes

When you call lire, you pass H, W and C to the function. These are pointers and they are not initialized and therefore you get a crash here in lire.

*H = cinfo.output_height;

You need to call the lire function like this:

int H;
int W;
int C;

....

lire(fichier, &H, &W, &C);