2017-06-04 55 views
-3

无效地址,它会引发错误:是什么原因导致当我运行我的程序指定RtlValidateHeap

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"); 
} 

我真的不明白,什么是错的,所以我希望您能够帮助我。

+0

欢迎来到Stack Overflow。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –

+0

解决这些问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你应该[编辑]你的问题,以包含一个[Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)例子来重现你的问题,以及你在调试器中所做的观察。 –

回答

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失败并返回一个空指针,则会丢失原始指针,并且会发生内存泄漏。

+1

....或者在C++中根本不使用malloc等。 –

相关问题