-6

The code below takes a window of size windowSize and shift the window by some shiftSize samples in each iteration.

I did the unusual "printf()" debugging and got that the code is giving error at segmentation fault. Can somebody tell me what the error is?

Code:

 #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <tgmath.h>
    int main ()
    {

        FILE *fp, *in   ;

        in = fopen ("controlFile.txt", "r");

        if (in == NULL) {
          fprintf(stderr, "Can't open input file in.list!\n");
          exit(1);
        }

        char equalTo, commandType[20];
        int commands[3]; int i=0;

        while (!feof(in)){

                fscanf(in, "%s %c %d\n", commandType, &equalTo, &commands[i]);
                printf("%s %c %d\n", commandType, equalTo, commands[i]);
                i++;
        }

        fclose(in);

        fp = fopen ("OriginalData.txt", "r");

        if (fp == NULL) {
          fprintf(stderr, "Can't open input file in.list!\n");
          exit(1);
        }

    //Note: time is milliseconds. Therefore, multiplying factor is 1000
        int mulFactor =1000;

        int samplesPerSecond = commands[0];

        int windowSize = floor((commands[1]*mulFactor)/samplesPerSecond); //This will be our array size or rank for cuda Program

        int shiftSize = floor ((commands[2]*mulFactor)/samplesPerSecond);

        int fileCounter  = 0, breakFlag=0;
        int allocationSize = 100;
        float *values, test;

        values = (float*) malloc (100*sizeof(float));

        if (values==NULL)
                {
                        printf("Error allocating memory!");
                        exit (1);
                }
        int localCounter = 0;
        int arrayCounter = 0;
        int copyCounter = windowSize - shiftSize;
//      printf("SamplesPerSecond: %d\n windowSize: %d\n shiftSize: %d\n copyCounter: %d\n", samplesPerSecond, windowSize, shiftSize, copyCounter);
        int temp;
        float* check;
        while (!feof(fp)){
                localCounter = 0;
                if (fileCounter==0){
                        while (!feof (fp) && localCounter!=windowSize){
                                fscanf(fp, "%f", &values[arrayCounter]);
                                printf("%f\n", values[arrayCounter]);
                                localCounter++;
                                fileCounter++;
                                                      arrayCounter++;
                                //printf("%f\n", values[arrayCounter]);
                                if (sizeof(values)/sizeof(float)==arrayCounter-1){
                                        values = (float*)realloc (values, (size_t)(allocationSize*sizeof(float)));
                                        if (values==NULL){
                                                printf("Cannot allocate memory\n");
                                                exit(1);
                                        }
                                }
                        }
                }
                else{
                        temp = copyCounter;
                //      printf("Here\n"); 
                        while (temp!=0 && !feof(fp)){
                                  //if (feof(fp)) {printf ("Been Here\n");breakFlag = 1; break;}
                                values[arrayCounter] = values [arrayCounter-copyCounter];
                                printf("%f\n", values[arrayCounter]);
                                temp--;
                                arrayCounter++;
                                localCounter++;
                                if (sizeof(values)/sizeof(float)==arrayCounter-1){
                                        values= (float*)realloc (values, allocationSize*sizeof(float));
                                        if (values==NULL){
                                                printf("Cannot allocate memory\n");
                                                exit(1);
                                        }
                                }

                        }
                         while (localCounter!=windowSize && !feof(fp)){
                                fscanf(fp, "%f", &values[arrayCounter]);
                                printf("%f\n", values[arrayCounter]);
                                localCounter++;
                                fileCounter++;
                                               arrayCounter++;
                                if (sizeof(values)/sizeof(float)==arrayCounter-1){
                                       values= (float*)realloc (values, allocationSize*sizeof(float));
                                        if (values==NULL){
                                                printf("Cannot allocate memory\n");
                                                exit(1);
                                        }
                        }
                        }
                }
        }
        fclose(fp);
        //int numOfFrames = floor((fileCounter-1)/shiftSize);  //Count the number of lines when fp is increasing
        //int j;
/*      for(j=0; j<(sizeof(values)/sizeof(float)); j++){
                printf ("%f\n", values[j]);
        }
*/
        return 0;
}
trincot
  • 317,000
  • 35
  • 244
  • 286
Developer by Blood
  • 155
  • 1
  • 3
  • 11
  • 2
    Hmmm... you couldn't have culled the code to the minimum required to display the error? I don't really feel like going through all that to find the point where it goes wrong... – DevSolar Sep 05 '14 at 14:24
  • Check int commands[i] when you do i++ because of definition int commands[3]; – Leo Chapiro Sep 05 '14 at 14:26
  • Why is your first `while` loop go unbounded? You could be accessing elements for those arrays that are out of bounds. – PaulMcKenzie Sep 05 '14 at 14:29
  • 1
    Don't check `feof()` *before* doing I/O, it doesn't work like that. – unwind Sep 05 '14 at 14:30
  • 1
    Sizeof doesn't do what you think.`if (sizeof(values)/sizeof(float)...` is completely wrong – joop Sep 05 '14 at 14:35
  • In that first `while` loop, if that loop iterates more than 3 times, you're accessing `commands[i]`, which is out of bounds. It looks like most of your loops are unsafe, as they do not ensure that the indices being used are in bounds of the arrays they're accessing. – PaulMcKenzie Sep 05 '14 at 14:39
  • @joop: Not wrong, just always 1 (with 32bit pointers) or 0 (with 64bit pointers). ;-) The fun thing is, if that condition actually evaluates to `true` (i.e. by accident), he `realloc()`s `values` from `100 * sizeof( float )` to `100 * sizeof( float )`, since he never increases `allocationSize`... two fails in one construct. ;-) – DevSolar Sep 05 '14 at 14:54
  • @DevSolar That is what I summarised as *completely wrong* ... – joop Sep 05 '14 at 14:59
  • @PaulMcKenzie, that while loop is going okay, nothing to worry about that. I could add some `i – Developer by Blood Sep 05 '14 at 17:10
  • @joop @DevSolar: Can you explain me why `if (sizeof(values)/sizeof(float)` is wrong, intuitively it seems correct to me :/ – Developer by Blood Sep 05 '14 at 17:15
  • 1
    `sizeof (values)` means: size of a pointer to float (`values` is a pointer to float) `sizeof (float)` is the size of a float. Dividing them will probably yield 1 or 2, depending on your platform. Comparing the result to `arrayCounter-1` will often give `not equal` as a result. (but this will **not** depend on the previously allocated size of the object that values points to, which is clearly what you intend) – joop Sep 08 '14 at 08:24

1 Answers1

2

1) You check feof() first, then do a fscanf(), and then don't check its return value (or re-check feof() at the very least. (You might have been right at the end of the file prior to the fscanf() call, or the configuration file might be malformed, but you wouldn't detect this with your code.)

2) Your index range checks (and assorted realloc()s) look dodgy. But there is absolutely no chance I'll be doing a runtime analysis of your code, especially since I don't have an input file example to go with.

Do some Machete Debugging...

Edit: After joop's comment pointed me toward the fine print of your realloc() (and the if statement around it), in absence of a comment explaining how exactly you expect this to work out, I'll say that you are invoking undefined behaviour there.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • So can you help me if I provide sample input? I am an amateur programmer in C and I'm getting really desperate to make this happen. – Developer by Blood Sep 05 '14 at 20:38
  • @DeveloperbyBlood: There has been lots of good, nay, **vital** advice given in this thread already, beyond "sample input needed". The link I posted, for example, should give a valuable lesson. I suggest you step back from "wanting this program to happen" (which is a bad premise to start with for a beginner), and take your time familiarizing yourself with the language, its pitfalls and its good practices. The code you posted is basically FUBAR, and requires a re-thinking and a rewrite. You can fix this yourself, with patience, and become a better programmer in the process. – DevSolar Sep 06 '14 at 06:25
  • So, I went back and read the syntax, return types and usage of realloc(), sizeof() functions and realized where I was wrong. Thanks DevSolar for motivating and @joop for emphazising the _crucial_ mistake - that mistake made me learn a lot. – Developer by Blood Sep 06 '14 at 07:25