【问题标题】:Dynamic memory allocation giving access violation(s)动态内存分配导致访问冲突
【发布时间】:2013-03-07 03:08:45
【问题描述】:

当我为十六进制数组中的缓冲区分配空间时,我的代码不断中断(即抛出访问冲突异常)。

我在 main 中将十六进制数组声明为两个星形指针,并通过引用传递它。

ma​​in.cpp 中的某处

char ** hexArray = nullptr;

fileio.cpp 中的某处

void TranslateFile(char * byteArray, char **& hexArray, int numberOfBytes, char buffer[])
{
int temp = 0;

//Convert bytes into hexadecimal
for(int i = 0; i < numberOfBytes; i++)
{
    //Convert byteArray to decimal
     atoi(&byteArray[i]);

     //Set temp equal to byteArray
     temp = byteArray[i];

     //Convert temp to hexadecimal and store it in hex array
     itoa(temp, buffer, 16);

     //Allocate room for buffer
     hexArray[i] = new char[strlen(buffer) + 1]; //CODE BREAKS HERE

     //Copy buffer into newly allocated spot
     strcpy(hexArray[i], buffer);
}
}

【问题讨论】:

  • 尝试使用 C++ 而不是 C,例如vector&lt;string&gt; hexArray;.
  • 您是否在任何地方分配hexArray?你不能分配给hexArray[i],除非你已经先在某处完成了hexArray = new char*[count]
  • 哇 5 分钟内有 5 个答案!

标签: c++ pointers dynamic-memory-allocation


【解决方案1】:
char ** hexArray = nullptr;

hexArray 未初始化。

hexArray[i] = new char[strlen(buffer) + 1]; //CODE BREAKS HERE

您取消引用hexArray,但它未初始化,因此您的程序会产生未定义的行为。您需要对其进行初始化,并且根据您的代码示例,它必须指向 至少 numberOfBytes 元素。

hexArray = new char *[numberOfBytes];

现在hexArray 是一个已初始化的指针,它指向numberOfBytes 未初始化的指针。

【讨论】:

  • @MrPickle5:别忘了,new[]ed 必须是delete[]d。智能指针是一种方法,但在这种情况下,std::vector&lt;std::string&gt; 可以说是更好的方法。
【解决方案2】:

您需要为外部数组分配内存。 从你的例子来看,它可能是:

hexArray = new char *[numberOfBytes];

【讨论】:

  • 听起来你需要为自己分配更多内存:)
【解决方案3】:

您不为hexArray 本身分配空间。你做了什么

 //Allocate room for buffer
 hexArray[i] = new char[strlen(buffer) + 1]; //CODE BREAKS HERE

正在为hexArray 的元素分配内存。

所以你应该把代码:

hexArray = new char*[numberOfBytes];

在进入 for 循环之前。

【讨论】:

    【解决方案4】:

    char ** 要么是 char * 的数组,要么是指向 char * 的指针。无论哪种方式,您都需要先分配一些东西才能执行hexArray[i]

    main.cpp 中的某处:

    hexArray = new char *[NUM_CHAR_PTRS];
    

    稍后...

    hexArray[i] = new char[strlen(buffer) + 1];
    

    【讨论】:

      【解决方案5】:

      hexArray 中的 numberOfBytes 条目是否已分配?

      使用strnlen 代替strlen 或者更好的是std::string。你知道buffer是否被终止(也就是说,它是TranslateFile的合同的一部分)吗?

      【讨论】:

        猜你喜欢
        • 2012-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-22
        相关资源
        最近更新 更多