在制作我自己的程序期间,我一直在 GDB 中尝试我的程序,但是当我运行不带 -g 的编译时,它给出了意想不到的结果,问题 从第二个命令开始的结果少于或等于 4 个字母
“帮助”(这种情况持续出现在每 4 个字母的命令中,例如停止和退出)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ncurses.h>
int curs; /*curs Used for Cursor*/
int Nullpos;
char *cmd;
void ShowCMD()
{
int Strlen = strlen(cmd) ;
printw("\nFull Command: %s\n NullPosition = %d\n", cmd, Nullpos);
for(int i = 0 ; i < Strlen ; i++ )
{
printw("Char %d : %u %c [] \n",i, cmd[i], cmd[i]);
}
printw("Char %d : %u [] \n",Strlen, cmd[Strlen]);
}
int AddNUllChar(char *Str)
{
int nullpos= 0;
for(int i = 0; (Str[i] <= 127 && Str[i] >= 0) && i < strlen(Str); i++)
nullpos = i;
Str[nullpos + 1 ] = (char)0;
return nullpos;
}
int IsInAllowedChars(char c)
{
if (c >= 32 && c <= 57)
return 1;
if (c >= 63 && c <= 90)
return 1;
if (c >= 95 && c <= 122)
return 1;
return 0;
}
void srvr_cmd()
{
e:;
curs = 0;
cmd = malloc(1024 * sizeof(char));
char ch;
while (1)
{
if((ch = getch()) == ERR)
continue;
if(ch > 127 || ch < 0 || ch == 10)
{
break;
}
if (IsInAllowedChars((ch)))
{
printw("%c", ch,ch);
cmd[curs] = ch;
curs++;
}
}
Nullpos = AddNUllChar(cmd);
cm:;
ShowCMD();
free(cmd);
goto e;
}
int main(int argc, char *argv[])
{
clear();
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
srvr_cmd();
return 0;
}
主要问题是
AddNUllChar()
。我必须假设它应该将终止空字符添加到字符数组中。因此,当输入函数时,数组尚未以 null 终止。如果是这样,您不能调用 strlen()
,因为它取决于空字符。
AddNUllChar()
将具有未定义的行为。这一切都取决于 cmd
中的字节,它是未定义的,因为 malloc()
不会清除它。
就目前情况而言,
AddNUllChar()
无法修复。相反,请将其删除并更换:
Nullpos = AddNUllChar(cmd);
与:
cmd[curs] = 0;
Nullpos = curs;
请注意,
Nullpos
现在的值与原始版本相比偏移了 1。现在它实际上指向带有空字符的数组元素。