calloc/malloc 并读取奇怪的行为?

标签 c dynamic-memory-allocation system-calls

我试图保留一个动态分配的字符串数组,这些字符串是使用 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/

相关文章:

C编程: Finding max in a file string

c - 输入流的队列出队入队错误

c - 逻辑帮助 : Calculating primes of a range of numbers with multiple threads

c - 程序在运行时在提供输入时崩溃

c - 结构数组中的内存分配

perl - 有什么可靠的方法来对文件列进行排序吗?

linux - 2 个或更多 fork 系统调用如何工作?

c - scanf:内部带有宏(#define 常量)的模板

C:传递给函数一个结构指针数组,每次都动态重新分配

macos - 解释 dtruss 输出,如 “psynch_cvwait(...) = -1 Err#316”