C用printf打印极其奇怪的值 [英] C printing extremely weird values with printf

查看:50
本文介绍了C用printf打印极其奇怪的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写此帖子,因为我设法找出了问题所在.输出异常中断的问题是由于动态内存分配不正确.

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.

所以我有一个名为Catalog的结构,该数组位于其中,并且该数组指向另一个名为Books的结构.

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

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

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.

推荐答案

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

您的打印结果会给出答案.您忘记了字符串上的空终止符,而printf入侵了下一个字段,直到到达空终止符为止.

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.

这是一个最小的例子

#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;
}

这篇关于C用printf打印极其奇怪的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆