【问题标题】:`read` in C hangs the program when string of length more than 16 entered当输入长度超过 16 的字符串时,C 中的 `read` 会挂起程序
【发布时间】: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


【解决方案1】:

我一直在测试您的代码。缺点是:你有一个指针,它不指向任何地方。我解决了它为您的字符串(字符数组)保留和分配内存。我将发布工作代码:

#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] = '\0';
    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] = '\0';
    printf("\"%s\" \n read returned: %i; NUL at: %u", s, a, strlen(s));
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2016-05-16
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2014-02-16
    • 2021-03-23
    相关资源
    最近更新 更多