C语言字母数字检查坏字符
C language alphanumeric check for bad chars
我的 C 代码完全可用:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdint.h>
int isAlphaNum(char *str) {
for (int i = 0; str[i] != '[=10=]'; 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;
}
以下是从终端复制的:
但是当我通过这样的套接字接收输入时:
90a41ae8477a334ba609e06cujdikj#%&%$@$Dkdfsノ,ᅵハ"]モ {ᆳf
或
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒814
程序崩溃
在这部分:
for (int i = 0; str[i] != '[=13=]'; i++)
if (!isalnum(str[i]))
我使用了@chqrlie 提供的函数并且有效:
已编辑
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");
}
一切正常
感谢帮助
您的代码中存在问题,但它不太可能在 GNU/linux 系统上引起问题,但可能会在其他系统上引起问题:如果 str[i]
有,则 isalnum(str[i])
有未定义的行为一个负值,如果字符串包含 8 位字节并且默认情况下 char
类型是有符号的,则这是可能的。 isalnum()
应该只传递 unsigned char
类型的值或特殊的负值 EOF
.
函数应该这样写:
#include <ctype.h>
int isAlphaNum(const char *str) {
while (*str) {
if (!isalnum((unsigned char)*str++))
return 0;
}
return 1;
}
你关于 通过套接字接收输入的评论 提示我怀疑你不是 null 终止通过套接字接收的字符串。这可能会导致 isAlphaNum()
读取超出数组的末尾,如果在内存映射区域(过去称为 段 在古代 Multics 系统中)。
我的 C 代码完全可用:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdint.h>
int isAlphaNum(char *str) {
for (int i = 0; str[i] != '[=10=]'; 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;
}
以下是从终端复制的:
但是当我通过这样的套接字接收输入时:
90a41ae8477a334ba609e06cujdikj#%&%$@$Dkdfsノ,ᅵハ"]モ {ᆳf
或
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒814
程序崩溃 在这部分:
for (int i = 0; str[i] != '[=13=]'; i++)
if (!isalnum(str[i]))
我使用了@chqrlie 提供的函数并且有效: 已编辑
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");
}
一切正常 感谢帮助
您的代码中存在问题,但它不太可能在 GNU/linux 系统上引起问题,但可能会在其他系统上引起问题:如果 str[i]
有,则 isalnum(str[i])
有未定义的行为一个负值,如果字符串包含 8 位字节并且默认情况下 char
类型是有符号的,则这是可能的。 isalnum()
应该只传递 unsigned char
类型的值或特殊的负值 EOF
.
函数应该这样写:
#include <ctype.h>
int isAlphaNum(const char *str) {
while (*str) {
if (!isalnum((unsigned char)*str++))
return 0;
}
return 1;
}
你关于 通过套接字接收输入的评论 提示我怀疑你不是 null 终止通过套接字接收的字符串。这可能会导致 isAlphaNum()
读取超出数组的末尾,如果在内存映射区域(过去称为 段 在古代 Multics 系统中)。