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



当我运行程序时,会引发错误:

invalid address specified to RtlValidateHeap( 00530000, 00A39B18 )

我认为这是因为Realloc,但我不明白为什么。而且我必须使用malloc,realloc和免费而不是新的和删除。我的.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] = '';
}
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] = '';
    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");
}

我真的不明白怎么了,所以我希望你能帮助我。

问题在这里:

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

第一行分配内存,并将mas指向新分配的内存。第二行将mas彻底完全在其他地方。在这里,您不仅应该将指针分配给其他地方,还应将指针指向其他位置,而是使用e.g.的字符串 copy strcpy

使用您现在拥有的代码

b = "ASD";

您将b.mas指向字符串文字中的第一个字符。然后,当您做

b = a;

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


在另一个注意事项上,您切勿将其分配给您传递给realloc的指针。如果realloc失败并返回零指针,则将丢失原始指针并将具有内存泄漏。