gpt4 book ai didi

c - C 中奇怪的 malloc 行为

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:16 24 4
gpt4 key购买 nike

我有以下 ANSI C 代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
char *buffer = 0;
int length = 0;
FILE *f = fopen("text.txt", "r");
if(f) {
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = malloc(length);
fread(buffer, 1, length, f);
fclose (f);
}
printf("File size: %d\nBuffer size: %d\nContent: %s\n=END=", length, strlen(buffer), buffer);
return 0;
}

由于某种原因,在 malloc 分配了比需要更多的内存并从内存中输出额外的垃圾,例如:第一次运行:

File size: 12Buffer size: 22Content: 123456789012les=$#▬rW|=END=

第二次运行:

File size: 12Buffer size: 22Content: 123456789012les↔1↕.'=END=

第三次运行:

File size: 12Buffer size: 22Content: 123456789012les=▬kπà=END=

有人可以帮我解决这个问题并解释为什么我的版本表现得很奇怪吗?我使用 MingW TDM-GCC 4.9.2 32bit 编译 (gcc)

最佳答案

你有undefined behavior (this 解释了为什么你应该害怕 UB)-因为 buffer overflow .您忘记添加终止空字节。

更换有问题的线路:

    // WRONG CODE:
buffer = malloc(length);
fread(buffer, 1, length, f);

    buffer = malloc(length+1);
if (!buffer)
{ perror("malloc"); exit(EXIT_FAILURE); };
memset (buffer, 0, length+1);
if (fread(buffer, 1, length, f) < length)
{ perror("fread"); exit(EXIT_FAILURE); };

(您可以只将结束字节归零;我更喜欢使用 memset 清除整个缓冲区)

顺便说一句,ANSI C 已经过时了。你应该使用 C11兼容编译器(例如 最近 GCC 用作 gcc -std=c11 -Wall -Wextra -g)和 objective-c 11 兼容(或至少 C99 )。学习使用调试器(例如 gdb )

仔细阅读 malloc(3) 的文档, fread(3) , perror(3)等等……

关于c - C 中奇怪的 malloc 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com