Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language alphanumeric check for bad chars

I have this C code fully working:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h> 
#include <stdint.h>

int isAlphaNum(char *str) {
    for (int i = 0; str[i] != '\0'; i++)
        if (!isalnum(str[i]))
            return 0;
    return 1;
}

int main() {
    char *user_string = "abcdedf0123456789ABCD";
    if (isAlphaNum(user_string)) {
        printf(" is valid \n");
    } else {
        printf(" is not valid \n");
    }
    printf(" \n end \n");
    return 0;
}

the following is copied from terminal:

but when I receive input via socket like this:

90a41ae8477a334ba609e06cujdikj#%&%$@$Dkdfsノ,ᅵハ"]￘モ {ᆳf

or

▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒814

the program crashes at this part:

for (int i = 0; str[i] != '\0'; i++)
    if (!isalnum(str[i]))

I used the function by @chqrlie and works: edited

int isAlphaNum(const char *str) {
    //this message is printed , then craches
    printf("pass isAlphaNum userinput = %s\n" , str);
    while (*str) {
        if (!isalnum((unsigned char)*str++))
            return 0;
    }
    return 1;
}

if (isAlphaNum(userinput)) {
    printf(" success ;) \n");
}

all ok now thanks for the help

like image 855
Mohammed Ahmed Avatar asked Dec 02 '25 09:12

Mohammed Ahmed


1 Answers

There is an issue in your code, but it is unlikely to cause the problem on GNU/linux systems, but might on other ones: isalnum(str[i]) has undefined behavior if str[i] has a negative value, which is possible if the string contains 8-bit bytes and the char type is signed by default. isalnum() should only be passed values of the type unsigned char or the special negative value EOF.

The function should be written this way:

#include <ctype.h> 

int isAlphaNum(const char *str) {
    while (*str) {
        if (!isalnum((unsigned char)*str++))
            return 0;
    }
    return 1;
}

Your remark about receiving input via socket prompts me to suspect that you are not null terminating the string received via a socket. This could cause isAlphaNum() to read beyond the end of the array and cause a segmentation fault if there is no null byte until the end of the memory mapped area (which used to be called a segment in ancient Multics systems).

like image 174
chqrlie Avatar answered Dec 04 '25 01:12

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!