【发布时间】:2018-04-05 21:37:34
【问题描述】:
我制作了以下程序,它使用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] = '\0';
printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
return 0;
}
我在这里期望的是,它会在用户输入换行符之前获取字符。然后它将'\n' 字符替换为'\0',并打印出来。
程序运行良好,直到我在 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 有什么特别之处? 发布脚本:我使用 string.h 只是为了获取字符串的长度。一旦我的程序开始运行良好,我将删除它。
【问题讨论】:
-
你的缓冲区
s没有指向任何分配的内存 -
仅供参考 - 这是“未定义的行为”。在 c 标准世界中
-
使用未初始化的指针会导致未定义的行为。挂起发生在一定大小的输入上只是巧合。
-
sigh 第 113444223 次:指针不是数组!为什么要用指针而不是数组?
-
对不起,社区。现在,当我初始化
s(通过将其设为数组或通过malloc)时,它正在工作。谢谢,社区。span>
标签: c system-calls low-level-io