当读取长度超过16的字符串时,C中的`read`挂起程序

时间:2018-04-05 21:37:34

标签: c system-calls low-level-io

我制作了以下程序,使用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 来获取字符串的长度。一旦我的程序开始正常运行,我将删除它。

1 个答案:

答案 0 :(得分:3)

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

#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;
}
相关问题