Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strncmp fails in parser function

Tags:

c

embedded

I can't find the problem in my parse() function. Short intro: I'm sending "boot\r\n" from my terminal program, the parse() function gets called, the strncmp(buffer, "boot",4) never gets into the if branch?? At the moment I can't see the wood for the trees. Afterwards the string which is returned from the parse() function is given to the remove_cr_lf_chars() function. I need to remove these characters to be able to compare the string with image names, which of course don't have any '\r' or '\n' characters.

static char *parse(void)
{
    static char buffer[100];
    char *p = buffer;
    char c;

    do {
        while (!(USART1->SR & USART_FLAG_RXNE));
        *p++ = c = ((char)USART1->DR);
    } while (c != '\r' && p-buffer < sizeof buffer-1);
    *p = '\0';

    if (strncmp(buffer, "boot", 4))
    {
        p = buffer+4;
        /* skip to argument, p might point to '\0' if none */
        while (*p != '\0' && (*p == ' ' || *p == '\r')) p++;
            return p;
    }
    return NULL;
}

static void remove_cr_lf_chars(char *dst)
{
    for (; *dst != '\0'; dst++)
        if (*dst != '\r' && *dst != '\n') dst++;
    *dst = '\0';
}
like image 827
arge Avatar asked May 31 '26 09:05

arge


2 Answers

This is because strncmp returns 0 when there is a match. You need to invert your condition:

if (!strncmp(buffer, "boot", 4)) ... // Means "if buffer is equal to "boot" "

Return value: Returns an integral value indicating the relationship between the strings: A zero value indicates that the characters compared in both strings form the same string. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.

like image 118
Sergey Kalinichenko Avatar answered Jun 02 '26 23:06

Sergey Kalinichenko


strncomp returns 0 if the two compared strings are equal. Hence, you need to modifiy your condition at line 13. For instance, you could write :

if ( strncmp(buffer, "boot", 4) == 0)
like image 40
MikeySec Avatar answered Jun 03 '26 00:06

MikeySec