为什么在这种情况下出现细分错误?

时间:2020-04-19 12:30:42

标签: c segmentation-fault

我正在准备Sierpinski Triangle,并且一切正常,但它显示了Segmenation Fault,我不知道我应该在代码中更改什么。 这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#define  t 32
#define  x 65

void display(char s[t][x])
{
  int i,j;

     for (i = 0; i < t; i++){//algorithm
         for (j = 0; j <= x ; j++){

             if ((s[i][j] == '0' && s[i][j+1] == '0' && s[i][j + 2] == '1') || (s[i][j] == '1' && s[i][j + 1] == '0' && s[i][j + 2] == '0'))
                 s[i+1][j+1] = '1';
             else
                 s[i+1][j+1] = '0';
         }
     }

    for (i = 0; i < t; i++){//printinng
        for (j = 0; j < x; j++){
            if (s[i][j] == '1') printf("X");
            else printf(" ");
        }
        printf("\n");
  }
}
int main() {
  char sierpinski[t][x];
  int i;
  int y = (x/2);//srodek 
  for(i=0;i<x;i++){//first row
    if(i == y) sierpinski[0][i] = '1';
    else sierpinski[0][i] = '0';
  }
    display(sierpinski);
  return 0;
}

2 个答案:

答案 0 :(得分:4)

只需在您的代码上尝试使用地址消毒剂处理clang

$ clang++-9 -fsanitize=address c.cc -o test && ./test
=================================================================
==14763==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd7c8ff160 at pc 0x0000004c53ea bp 0x7ffd7c8fe860 sp 0x7ffd7c8fe858
WRITE of size 1 at 0x7ffd7c8ff160 thread T0

这意味着您在数组边界之外触摸内存。确实符合

if ((s[i][j] == '0' && s[i][j+1] == '0' && s[i][j + 2] == '1') || (s[i][j] == '1' && s[i][j + 1] == '0' && s[i][j + 2] == '0'))

索引j + 2可以大于x - 1

答案 1 :(得分:0)

您需要在if检查中检查范围

`

#include <stdio.h>

#include <stdlib.h>
#define  t 32
#define  x 65

void display(char s[t][x])
{
  int i,j;

 for (i = 0; i < t; i++){//algorithm
     for (j = 0; j < x ; j++){
         if(j+1 < x && i+1 < t) { // Add this
            if ((s[i][j] == '0' && s[i][j+1] == '0' && s[i][j + 2] == '1') || (s[i][j] == '1' && s[i][j + 1] == '0' && s[i][j + 2] == '0'))
                 s[i+1][j+1] = '1';

            else
                 s[i+1][j+1] = '0';
         }
     }
 }

for (i = 0; i < t; i++){//printinng
    for (j = 0; j < x; j++){
        if (s[i][j] == '1') printf("X");
        else printf(" ");
    }
    printf("\n");
 }

}

  int main() {
  char sierpinski[t][x];
  int i;
  int y = (x/2);//srodek
  for(i=0;i<x;i++){//first row
if(i == y) sierpinski[0][i] = '1';
else sierpinski[0][i] = '0';

}

 display(sierpinski);
 return 0;

}