gpt4 book ai didi

c - 即时调整 char* 的大小 - 为什么此代码*有效*?

转载 作者:太空狗 更新时间:2023-10-29 15:13:26 24 4
gpt4 key购买 nike

<分区>

我正在试验 malloc 和 realloc,并为以下问题提出了一些代码:

I want to create a string of unknown size, without setting any limit. I could ask the user for a nr of chars, but I rather resize the str as the user types each character.

所以我尝试使用 malloc + realloc 来做到这一点,我的想法是每次用户输入一个新的字符时,我都使用 realloc 来请求 +1 block 内存来保存该字符。

在尝试实现这一点时,我犯了一个错误,最终做了以下事情:

int main () {
/* this simulates the source of the chars... */
/* in reality I would do getch or getchar in the while loop below... */

char source[10];
int i, j;
for (i=0, j=65; i<10; i++, j++) {
source[i] = j;
}

/* relevant code starts here */

char *str = malloc(2 * sizeof(char)); /* space for 1 char + '\0' */
int current_size = 1;

i = 0;
while(i<10) {
char temp = source[i];
str[current_size-1] = temp;
str[current_size] = '\0';
current_size++;
printf("new str = '%s' | len = %d\n", str, strlen(str));
i++;
}

printf("\nstr final = %s\n", str);

return 0;

}

请注意,realloc 部分尚未实现。

我编译并执行了这段代码,得到了以下输出

new str = 'A' | len = 1
new str = 'AB' | len = 2
new str = 'ABC' | len = 3
new str = 'ABCD' | len = 4
new str = 'ABCDE' | len = 5
new str = 'ABCDEF' | len = 6
new str = 'ABCDEFG' | len = 7
new str = 'ABCDEFGH' | len = 8
new str = 'ABCDEFGHI' | len = 9
new str = 'ABCDEFGHIJ' | len = 10

我发现这些结果很奇怪,因为我预计程序会崩溃:str 有 2 个字符的空间,而代码在没有请求更多内存的情况下向 str 添加了 2 个以上的字符。根据我的理解,这意味着我在不属于我的内存中写入,因此它应该会出现运行时错误。

那么...为什么这行得通?

(编译器是 GCC 4.3.4。)

提前致谢。

编辑:其中一位评论者建议调用 free() 可能会导致发出错误信号。我尝试用上面的代码调用 free() 并且执行代码没有导致错误。但是,在源数组中添加更多项后,同样调用free,得到如下错误:

* glibc 检测到 ./prog: free(): invalid next size (fast): 0x09d67008 **

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