我试图保留一个动态分配的字符串数组,这些字符串是使用 c 中的 read 系统调用读取的。这是我正在尝试做的一个小示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void processInput() {
char ** array = (char **) calloc(20, sizeof(char*));
int arrayIndex = 0;
while(1) {
printf("Type something: ");
fflush(stdout);
char* buffer;
int readResult = read(0, buffer, 100);
array[arrayIndex] = (char*)calloc(readResult, sizeof(char));
}
}
但是,这会导致一些奇怪的问题:
Type something: a Type something: Type something: a Type something: Type something: abcdefg Type something: Type something: Type something: Type something: Type something: Type something: Type something: Type something:
这有什么解释吗?我似乎无法弄清楚为什么会发生这种情况。
最佳答案
替换:
char *buffer;
与:
char buffer[100];
维度与 read()
的参数一致,但您的字符串不会以 read()
结尾,因此您可能更愿意分配 101 个字节相反,并强制 null 终止它。分配空间时需要考虑额外的字节。
请注意,分配的空间并未使用。
在使用内存分配之前,您应该始终对它们进行错误检查。
由于您在循环之前只分配了 20 个指针,因此 while (1)
循环很危险,如果用户输入超过 20 行数据,可能会导致您超出分配的空间。
(请注意,如果用户重定向文件中的输入,您将不会读取 20 行;您将读取 20 个 100 个字符 block 中的 2000 个字符、换行符等,然后陷入崩溃区域。)
关于calloc/malloc 并读取奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8783804/