gpt4 book ai didi

c - 为什么我的字符串的大小会改变? (C)

转载 作者:行者123 更新时间:2023-12-01 12:38:41 25 4
gpt4 key购买 nike

    fseek(fp, 0L, SEEK_SET);
int i; char c;
i = 0;
for (c = getc(fp); c != EOF; c = getc(fp)) {
c = tolower(c);
file_string[i] = c;
i++;
}

在这段代码中,我读取了一个文件的每个字符,将其转换为小写,并将其放入一个字符串中。现在,假设我将 21 个字节 * sizeof(char) 分配给 file_string。有时,在此处显示的这段代码之后,strlen(file_string) 将返回 30,而不是预期的 20。也许我的指针算法有问题?我收集的一些东西:

1 - 这只在某些时候发生。

2 - 我已确保将正确数量的字节分配给 file_string(这恰好发生在这段代码之前的行)。代码如下:

fseek(fp, 0L, SEEK_END);
file_len = ftell(fp);
file_string = malloc( sizeof(char) * (file_len+1) );

打印 file_len 输出预期的长度。

3 - 我打印出 i 的值以确保它迭代的次数与 file_string 的长度相同,确实如此。

4 - 现在,直接在这段代码之后(关闭文件之后),当我打印出 file_string 的长度时,有时它会突然增加到更大的尺寸。这一直在我的代码的其他地方引起问题。

现在,我认为我可以将空终端字符插入其中并解决问题(也许这会进一步导致错误),但我更想知道这里发生了什么。

下面是我调试的一个例子,展示前后大小的变化。请记住,之前的长度对应于 file_len 变量。

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> file_len: 24
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 0
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 1
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 2
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 3
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 4
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 5
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 6
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 7
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 8
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 9
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 10
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 11
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 12
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 13
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 14
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 15
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 16
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 17
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 18
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 19
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 20
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 21
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 22
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>i: 23
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> strlen(file_string): 30

最佳答案

Now, I figure I can just stick the null terminal character in there and fix the problem (maybe that will cause errors further down the line), but I would prefer to know what's going on under the hood here.

这就是真正的解决方案。 strlen 正在缓冲区中搜索 NULL 终止符,但没有找到,因为您从未添加过终止符。阅读代码后,您应该明确添加 NULL 终止符(即 file_string[i] = '\0')。

请记住,malloc 返回的存储没有归零,它基本上是随机数据(呃……malloc 返回的存储内容是未定义的)。发生的事情是您正在运行缓冲区的末尾并进入随机内存,它恰好在行的下方运行到零字节并假设这是字符串的末尾。

关于c - 为什么我的字符串的大小会改变? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27044231/

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