为什么我的char *在循环中分配了一个字符串,但之后是“(null)”?编译器错误?

时间:2014-09-08 11:22:58

标签: c++ c debugging pointers

我在访问我刚刚在我的程序中设置的数据时遇到了问题:计算机上说我char*的某些(null)[...] // in this loop I fill my array with strings for(theChildren_It = theChildren.begin(); theChildren_It != theChildren.end();theChildren_It++,noOfStrings++) { strings[noOfStrings] = (char*) malloc(400); strcpy(strings[noOfStrings],(*theChildren_It)->Name().c_str()); // Debug output FILE *out = fopen("[...]/Debugtext","a+"); fprintf(out, "INSIDE the loop: %i - %s -- %s\n", noOfStrings, (*theChildren_It)->Name().c_str(), strings[noOfStrings]); fclose(out); } // here I check the very first entry FILE *asdf = fopen("[...]/Debugtext","a+"); fprintf(asdf, "OUTSIDE the loop: %i - %s -- %s\n", noOfStrings, (*theChildren.begin())->Name().c_str(), strings[0]); fclose(asdf); [...] ,实际上不是 - 请参阅我的代码段:

因为我的代码更大,所以我要将其分解为更简单的源代码:

INSIDE the loop: 0 - ObjectA -- ObjectA
INSIDE the loop: 1 - ObjectB -- ObjectB
INSIDE the loop: 2 - ObjectC -- ObjectC


OUTSIDE the loop: 2 - ObjectA -- (null)

运行程序后,Debugtext中填充了如下行:

OUTSIDE the loop: 2 - ObjectA - ObjectA

我希望我发布的代码不会太少,但我不想让它过于复杂。

嗯,我不确定为什么会发生这种情况 - 这个例程在90%的情况下运行干净(意味着:大多数情况下它运行{{1}})。你可以说输入总是一样的 - 这就是为什么我认为可能存在编译器错误。

有谁知道为什么会这样?

亲切的问候

1 个答案:

答案 0 :(得分:4)

使用固定大小的数组时要小心缓冲区溢出。您有两个硬编码的上限:

  • 最大由于malloc(400)
  • ,字符串的长度为399个字符
  • 最大由于char* strings[400]
  • ,字符串数量为400

当超出其中任何一个限制时,会发生缓冲区溢出,并覆盖超出缓冲区边界的内存。这可能有各种令人讨厌和意想不到的效果(它是未定义的行为)。包括您观察到的行为(strings数组的第一个条目可能已被零覆盖,例如。)。