[英]How to detect run-time stack smashing/buffer overflow in C and enable gdb to exit gracefully with proper message.?
[英]Stack smashing/Buffer overflow in C
我有這個代碼
int Iminente(char tab[3][3], char comp, char jog, char str[3][3]){
int i, j, X = 0, val;
char col[4], diag[2][4];
strcpy(diag[0], &tab[0][0]); // Diagonal E-D C-B (= \ )
strcat(diag[0], &tab[1][1]);
strcat(diag[0], &tab[2][2]);
strcpy(diag[1], &tab[0][2]); // Diagonal D-E B-C (= / )
strcat(diag[1], &tab[1][1]);
strcat(diag[1], &tab[2][0]);
for(i = 0; i < 3; i++){
strcpy(col, &tab[0][i]); // Colunas
strcat(col, &tab[1][i]);
strcat(col, &tab[2][i]);
for(j = 0; j < 3; j++){
if(strcmp(str[j], tab[i]) == 0){ // Verifica linhas
Jogar(tab, comp, InvPosicao(i, j));
return 1;
}
if(strcmp(str[j], col) == 0){ // Verifica colunas
Jogar(tab, comp, InvPosicao(i, j));
return 1;
}
if(!X){ // Verifica diagonais
if(strcmp(str[j], diag[0]) == 0){
Jogar(tab, comp, InvPosicao(j, j));
return 1;
}else if(strcmp(str[j], diag[1]) == 0){
val = 2 - j;
Jogar(tab, comp, InvPosicao(val, j));
return 1;
}
}
}
X = 1;
}
return 0;
}
僅當我們到達指令return 0
時,才會發生錯誤。 我找不到確切的位置。 我只能說所有信息都是由我(而不是用戶)提供的,我根據預測的長度定義了變量。
這是井字游戲的一部分。 這是變量
tab - 3x3 table, each element is a char
comp - current computer char
jog - current player char
str - group of "strings" with 3 elements each with length 3 (null terminator not included)
i, j - iterators
X - "state" variable (not important)
val - not important
col - string with the current column
diag - group of "strings" with 2 elements each with length 4 (null terminator included)
值:
possible values for `str`:
char perder[3][3] = {{' ', jog, jog}, {jog, ' ', jog}, {jog, jog, ' '}};
char ganhar[3][3] = {{' ', comp, comp}, {comp, ' ', comp}, {comp, comp, ' '}};
value for `tab`:
char jogo[3][3] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; // Elements can be ' ', 'O', or 'X'
values for `jog` and `comp`:
'O' or 'X'
它與strcat()
和strcpy()
函數有關嗎?
正如@ John3136所提到的,我的代碼一團糟。
因此,為了解決該問題,我實現了一個向字符串添加字符的功能:
void AdicionaCar(char *s, char c){
int length = strlen(s);
s[length] = c;
s[length+1] = '\0';
}
並使用此函數替換了strcat
和strcpy
所有實例。
然后使用空終止符初始化變量diag
和col
,以便它們可以成為字符串。 將形式參數更改為指針(不是全部),現在函數標頭如下所示:
int Iminente(char (*tab)[3], char comp, char jog, char (*str)[3])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.