0

Constantly getting segmentation fault, and i'm not able to solve this. If the program runs the "encodeFile" - function, the program should be able to read the input file character by character and compress the character of a 2 bit value. The values will then be printed in the output file. I'm very new to this language. How do i solve this task?

//The function
void encodeFile(char *fpInputfile,char *fpOutputfile)
{
        FILE *fileInput = fopen(fpInputfile, "r");
        FILE *fileOutput = fopen(fpOutputfile, "w");

        if (!fileInput || !fileOutput){
            printf("ERROR MESSAGE: can not open the selected file \n");
            exit(1);
        }

        char symbols[4];
        char encodeB[4] = {0x00, 0x01, 0x02, 0x03};
        size_t c = fread(symbols, sizeof(char), 4, fileInput);

        while (c != 0){
            int i = 0;
            int j = 0;
            char temp = 0;
            while (c > 0){

                if (symbols[j] == ' '){
                    temp = encodeB[0];
                }
                else if (symbols[j] == ':'){
                    temp = encodeB[1];
                }
                else if (symbols[j] == '@'){
                    temp = encodeB[2];
                }
                else if (symbols[j] == '\n'){
                    temp = encodeB[3];
                }
                else{
                }
                j++;
                i |= temp << (c *2);
                c++;
            }
            //c = fread(symbols, sizeof(char), 4, fileInput);
            //fwrite(&temp, 1, 1, fileOutput);
        }
        fclose(fileInput);
        fclose(fileOutput);

    }
zuni buni
  • 23
  • 2

1 Answers1

0
while (c > 0){
   ...
   c++;
}

This is going to cause an infinite loop. The segmentation fault is from reading symbols[4], which is an access violation.

I strongly recommend learning how to step through code in a debugger if you want to use this language. Good luck!

m24p
  • 664
  • 4
  • 12
  • 1
    More specifically, the access violation and consequent segmentation fault is from attempting to read memory not belonging to the program, which in this case is happening via an attempt to read a putative element of `symbols` that is in fact well past the end of that array. – John Bollinger Sep 30 '14 at 21:21
  • Thanks I figured it out :) – zuni buni Oct 01 '14 at 05:23