开发者

Need explanation for odd for loop/scope problem

While starting on a program for getting a matrix's Reduced Row Echelon Form, I transferred my code for printing the array into its own function. As soon as I did this, I got a segfault. What puzzled me though, was the fact that an unrelated variable declaration (commented below) solved the segfault.

    #include <stdio.h>


int COLS = 3;
int ROWS = 3;

void PrintArray(int array[][COLS]);

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

   int i, ii = 0;

   FILE *file;

   file = fopen(argv[1], "r");

   int array[ROWS][COLS];

   fscanf(file, "%d %d", &ROWS, &COLS);

   while (!feof(file))
   {
      fscanf(file, "%d", &array[i][ii]);
      ii++;
      if (fgetc(file) == '\n') {
         i++;
         ii = 0;
      }
   }
   int j = 0, k = 0; //This solved the segfault.
   PrintArray(array);
   printf("\n");

   fclose(file);
   return 0;
}

void PrintArray(int array[][COLS]) //The printing function
{
   int j, k;
   for (j = 0; j <开发者_如何学运维 ROWS; j++)
      {
         for (k = 0; k < COLS; k++)
         {
            printf("%d", array[j][k]);
         }
         printf("\n");
      }
}

After a couple hours of debugging, I eventually figured out that it may have had something to do with the scope of the variables within the for loop.

To illustrate:

int COLS = 3;
int ROWS = 3;
int a; //declared globally

//main

   for (a = 0; a < ROWS; a++) {
      printf("for loop");
   }

works, but as soon as I declare "a" in main:

int COLS = 3;
int ROWS = 3;


//main
   int a; //declared in main
   for (a = 0; a < ROWS; a++) {
      printf("for loop");
   }

it doesn't work.

Also, if I replace the global variables with numbers, I still get a segfault, until I remove the line which originally fixed the segfault!

void PrintArray(int array[][3]) //COLS
{
   int j = 0, k = 0;
   for (j = 0; j < 3; j++) //ROWS
      {
         for (k = 0; k < 3; k++) //COLS
         {
            printf("%d", array[j][k]);
         }
         printf("\n");
      }
}

This appears to be as far as I can get to understanding the problem, so your help would be appreciated.


You are getting out of array bounds. The two extra variables lay right after the array on the stack, so you begin corrupting them instead of something else, that's why segfault is “solved” (it's not solved, of course, the bug is still there).

There are severe problems with that code:

  • Variable i is used without being initialized
  • The array size is always 3x3. Reading new values for ROWS and COLS does NOT resize the array. If e.g. you have read ROWS=4 and COLS=4 from file, you will corrupt the memory outside of that allocated for array.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜