当输入长度超过 16 的字符串时,C 中的 read 会挂起程序
`read` in C hangs the program when string of length more than 16 entered
我制作了以下程序,该程序使用 read
(C 中的系统调用)从用户(长度小于 100)获取 字符串。
#include<stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
char *s;
int a = read(0, s, 100);
s[a-1] = '[=10=]';
printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
return 0;
}
我在这里期望的是,在用户输入换行符之前它会获取字符。然后它将 '\n'
字符替换为 '[=14=]'
,并打印它。
在 stdin
中输入 15 个或更少的字符之前,该程序运行良好,但是当输入超过 16 个字符时,停止工作。
我的输入如下:
E:\My Files\Codes>a.exe
1234567890123456
"1234567890123456"
returned = 17; length = 16
E:\My Files\Codes>a.exe
12345678901234567
[My program hanged on this input.]
为什么只挂在16?这个2^2有什么特别之处?
Post 脚本:我使用 string.h 只是为了获取字符串的长度。一旦我的程序开始正常运行,我将删除它。
我一直在测试你的代码。缺点是:你有一个指向任何地方的指针。我解决了为您的字符串(字符数组)保留和分配内存的问题。我将 post 工作代码:
#include <stdlib.h> // It is needed for malloc, free, etc...
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
char *s = malloc(100*sizeof(char)); // Allocate memory with malloc
int a = read(0, s, 100);
s[a-1] = '[=10=]';
printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
free(s); // You need liberate memory before exit
return 0;
}
此外,解决此问题的其他方法是:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
char s[100]; // s is a char array of 100 elements
int a = read(0, s, 100);
s[a-1] = '[=11=]';
printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
return 0;
}
我制作了以下程序,该程序使用 read
(C 中的系统调用)从用户(长度小于 100)获取 字符串。
#include<stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
char *s;
int a = read(0, s, 100);
s[a-1] = '[=10=]';
printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
return 0;
}
我在这里期望的是,在用户输入换行符之前它会获取字符。然后它将 '\n'
字符替换为 '[=14=]'
,并打印它。
在 stdin
中输入 15 个或更少的字符之前,该程序运行良好,但是当输入超过 16 个字符时,停止工作。
我的输入如下:
E:\My Files\Codes>a.exe
1234567890123456
"1234567890123456"
returned = 17; length = 16
E:\My Files\Codes>a.exe
12345678901234567
[My program hanged on this input.]
为什么只挂在16?这个2^2有什么特别之处? Post 脚本:我使用 string.h 只是为了获取字符串的长度。一旦我的程序开始正常运行,我将删除它。
我一直在测试你的代码。缺点是:你有一个指向任何地方的指针。我解决了为您的字符串(字符数组)保留和分配内存的问题。我将 post 工作代码:
#include <stdlib.h> // It is needed for malloc, free, etc...
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
char *s = malloc(100*sizeof(char)); // Allocate memory with malloc
int a = read(0, s, 100);
s[a-1] = '[=10=]';
printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
free(s); // You need liberate memory before exit
return 0;
}
此外,解决此问题的其他方法是:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
char s[100]; // s is a char array of 100 elements
int a = read(0, s, 100);
s[a-1] = '[=11=]';
printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
return 0;
}