是什么原因导致为RtlValidateHeap指定的无效地址

时间:2017-06-04 16:15:12

标签: c++

当我运行程序时,它会抛出错误:

invalid address specified to RtlValidateHeap( 00530000, 00A39B18 )

我认为这是因为realloc,但我不明白为什么。我必须使用malloc,realloc和free而不是new和delete。 我的.h文件:

#pragma once

class String
{
private:
    char* mas;
    int n;
public:
    String();
    void EmptyStr();
    void print();
    void operator = (char* str);
    void operator = (const String &a);
    String operator+ (char* str);
    String operator + (const String &a);
    void operator += (char*);
    void operator += (const String &a);
    char &operator [] (int i);
};

我的.cpp文件:

#include"Strings.h"
#include<stdlib.h>
#include<iostream>

String::String()
{
    this->mas = NULL;
    this->n = 0;
}

void String::print()
{
    std::cout << this->mas << ' ' << this->n << std::endl;
}

void String::EmptyStr()
{
    this->mas = (char*)realloc(this->mas, sizeof(char));
    this->n = 0;
    this->mas[0] = '\0';
}

void String::operator =(char* str)
{
    this->n = strlen(str);
    this->mas = (char*)realloc(this->mas, (this->n + 1) * sizeof(char));
    this->mas = str;
}

void String::operator=(const String &a)
{
    this->mas = (char*)realloc(this->mas, (a.n + 1)* sizeof(char));
    this->n = a.n;
    *this = a.mas;
}

String String::operator+(char* str)
{
    String tmp;
    tmp.mas = (char*)malloc((this->n + strlen(str)+1) * sizeof(char));
    tmp.n = this->n + strlen(str);
    tmp.mas[0] = '\0';
    strcat(tmp.mas, this->mas);
    strcat(tmp.mas, str);
    return tmp;
}

String String::operator+(const String &a)
{
    String tmp;
    tmp.mas = (char*)malloc((this->n + a.n + 1) * sizeof(char));
    tmp.n = this->n + a.n;
    tmp = *this + a.mas;
    return tmp;
}

void String::operator+=(char* str)
{
    *this = *this + str;
}

我的主要.cpp文件

#include"Strings.h"
#include <iostream>

int main()
{
    String a, b, c;
    a = "Hello";
    b = "ASD";
    b = a;
    b.print();

    system("PAUSE");
}

我真的无法理解错误,所以我希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

问题在于:

this->mas = (char*)realloc(this->mas, (this->n + 1) * sizeof(char));
this->mas = str;

第一行分配内存,并使mas指向新分配的内存。第二行使mas完全指向其他地方。在这里,您不应该仅仅指向指向其他位置的指针,而是使用例如复制字符串。 strcpy

使用现在的代码,当你做

b = "ASD";

你使b.mas指向字符串文字中的第一个字符。然后当你做

b = a;

您在realloc调用中使用指向字符串文字的指针,这是错误的,因为您尚未通过mallocrealloc分配该内存。

另一方面,你永远不应该回到传递给realloc的指针。如果realloc失败并返回空指针,则会丢失原始指针并导致内存泄漏。

相关问题