C使用printf打印非常奇怪的值



我正在重写这篇文章,因为我设法解决了这个问题。我的输出异常中断的问题是由于不正确的动态内存分配造成的。

基本上,我需要为指向结构的指针数组分配内存,但数组本身嵌套在另一个结构中,嵌套让我有点困惑,我最终使它过于复杂

因此,我有一个名为Catalog的结构,我的数组在其中,该数组指向另一个名称为Books的结构。

当我最初为它分配内存时,我只为数组分配了内存,而不是指针数组:

catalog->arrayP = malloc(INITIAL_CAPACITY * sizeof( Books );
// But I should have done this:
catalog->arrayP = (Books *) malloc(INITIAL_CAPACITY * sizeof( Books );
// That first (Books *) was extremely important

我遇到的第二个问题是,当我试图更新内存以容纳更多的书时,我实际上是在减少它:

catalog->arrayP = realloc(catalog->arrayP, 2 * sizeof( catalog->arrayP));
// I did this thinking it would just increase the memory to twice that of what it currently was, but it didn't
cataloc->capacity = catalog->capacity * 2;
catalog->arrayP = realloc(catalog->arrayP, catalog->capacity * sizeof( catalog->arrayP));

因此,每当我需要增加指针数组时,我最终只为两本书分配了足够的内存,而不是当前的两倍。

Frankenstein; Or, The Modern Prometh..Shelley, Mary Woll.

你的打印结果有点泄露了答案。您忘记了字符串上的null终止符,printf侵入下一个字段,直到到达null终止符。

在接下来的田地里,它找不到更多的东西,入侵了更多的东西。

以下是的一个最小示例

#include <stdio.h>
#include <string.h>
struct test{
char test[37]; // space for 36 chars + null
char test2[16]; // space for 15 chars + null
};
int main(void) {
struct test Test;
strcpy(Test.test, "randomrandomrandomrandomrandomrandom"); // Copy the 37 bytes
strcpy(Test.test2, "notnotnotnotnot"); // Copy the 16 bytes
//Replace null terminator with trash for demonstration purposes
Test.test[36] = '1'; // replaces 37th byte containing the terminator () with trash
printf("%38s", Test.test); // should print randomrandomrandomrandomrandomrandom1notnotnotnotnot
return 0;
}

相关内容

最新更新