获取无法在地址错误时访问内存

时间:2013-11-13 12:41:53

标签: c++ gdb

我收到此错误:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400f8b in encryptFile (
inPath=<error reading variable: Cannot access memory at address 0x7fffff63a0f8>, 
outPath=<error reading variable: Cannot access memory at address 0x7fffff63a0f0>, 
key=<error reading variable: Cannot access memory at address 0x7fffff63a0e8>) at    main3.cpp:7
7   bool encryptFile(std::string& inPath, std::string& outPath, unsigned char * key) {

这是代码:

#include <fstream>
#include <iostream>
#include <stdlib.h>

#define buffersize 10240000

bool encryptFile(std::string& inPath, std::string& outPath, unsigned char * key)
{
  unsigned char mbuf[buffersize];
}

int main(int argc, char **argv)
{
  unsigned char k[32];
  std::string clear = "clear.bin";
  std::string crypt = "crypt.bin";
  encryptFile(clear, crypt, &k[0]);
}
然而,奇怪的是,如果我设置

#define buffersize 10240
一切正常。我做错了什么?

1 个答案:

答案 0 :(得分:4)

在大多数现代系统中,自动变量将被放置在堆栈上,因此您将溢出有限的堆栈空间。典型的堆栈大小介于1M to 8Mmbuf之间,大约为10M,大小为10240000。一个更好的选择是使用动态内存分配甚至更好,因为这是 C ++ 你只需使用std::vector而不必担心删除动态分配的内存当你完成。 Stack Overflow Problems涵盖了常见系统上的典型堆栈大小:

SunOS/Solaris   8172K bytes
Linux           8172K bytes
Windows         1024K bytes
cygwin          2048K bytes