I've been trying my program in GDB during the making of my own program but when I run the compiled without -g it gives unexpected results, the problem results from the 2nd Command Onwards that have less or equal to 4 letters
"Help" ( This case persists with every 4 letter command like stop & exit )
Expected : With GDB Received : Without GDB Note: This is how Letters are Read
#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;
}
The main problem is AddNUllChar()
. I must assume that it is supposed to add the terminating null character to the character array. So when the function is entered, the array is not yet null-terminated. If so, you cannot call strlen()
because it depends on the null character.
AddNUllChar()
will have undefined behavior. It all depends on the bytes in cmd
, which is undefined as malloc()
does not clear it.
As it stands, AddNUllChar()
cannot be fixed. Instead, remove it and replace:
Nullpos = AddNUllChar(cmd);
with:
cmd[curs] = 0;
Nullpos = curs;
Note that Nullpos
now has a value that is offset by 1 compared to your original version. It now actually points at the array element with the null character.