C printing extremely weird values with printf

▼魔方 西西 提交于 2021-01-29 12:32:20

问题


I am rewriting this post because I managed to figure out the problem. The problem with my extremely broken output was due to an improper dynamic memory allocation.

Basically I needed to allocate memory for an array of pointers that pointed to structs, but the array itself was nested inside of another struct and the nesting confused me slightly and I ended up over complicating it.

So I had a struct named Catalog, that my array was in and that array pointed to another struct named Books.

When I originally allocated memory for it I was only allocated memory for an array, not an array of pointers:

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

The second issue I was having was that when I was trying to update the memory to allow for more books I was actually decreasing it:

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));

So whenever I needed to grow my array of pointers I ended up just allocating enough memory for 2 books rather than double the current.


回答1:


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

Your printing results kind of give away the answer. You forgot the null terminator on your strings and printf invaded the next field until reached the null terminator.

In the following fields it couldn't find and invaded even more stuff.

Here's a minimal example

#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 (\0) with trash
  printf("%38s", Test.test); // should print randomrandomrandomrandomrandomrandom1notnotnotnotnot
  return 0;
}


来源:https://stackoverflow.com/questions/64508002/c-printing-extremely-weird-values-with-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!