My C code below is trying to remove the trailing white space from a string pointer. while testing the code I am getting a "Conditional jump or move depends on the uninitialized value(s)" a line 3. Since I am trying to read the length of a string pointer, do I need to initialize it?
void trim(char *s)
{
int i = strlen(s) - 1;
while (i > 0)
{
if (s[i] == ' ' || s[i] == '\t')
i--;
else /* where you see very first from the last nonwhite space*/
break;
}
s[i 1] = '\0';
}
function trim is called in another function which is reading input from commandline
char *UserInput()
{
char *input = (char *)malloc(120);
char command[120];
int len = read(STDIN_FILENO, command, 120 - 1);
int i;
for (i = 0; i < len; i )
{
if (command[i] == '\n')
{
break;
}
input[i] = command[i];
}
trim(input);
return input;
}
CodePudding user response:
Your copying of command
to input
character by character fails to terminate it with a NUL character, giving undefined behavior when you call strlen
on the parameter passed to trim
Fix:
input[i] = '\0';
trim(input);