random crashes on delete []
Hi, im having trouble trying to write the String class, following along with "C++ without Fear". and most of the time my destructor for my string class crashes on delete [] ptr;
heres the sources.
main.cpp
Code:
#include "string.h"
//#include <iostream>
//#include <windows.h>
using namespace std;
int main(int argc, char** argv) {
String str("hello world"); //crashes on this Strings destructor.
String str2;
String str3;
String tmp;
char *c = new char[500];
delete c; //works fine.
//cin.get();
return 0;
}
string.h
Code:
#ifndef STRING_H
#define STRING_H
//#include <cstring>
//#include <iostream>
class String {
private:
char *ptr;
public:
String();
String(const char *s);
String(const String &src);
~String();
operator char*(){return ptr;}
int operator==(const String &other);
int operator>(const String &other);
int operator<(const String &other);
String& operator=(char *s);
String& operator=(String &src);
private:
void cpy(char *s);
};
#endif /* STRING_H */
string.cpp
Code:
#include "string.h"
int strlen(const char *str){
int i = 0;
while(str[i] != '\0')
i++;
return i;
}
int strcmp(const char *c1, const char *c2){
int i = 0;
while(c1[i] == c2[i]){
if(c1[i] == '\0')
return 0;
i++;
}
if(c1[i] > c2[i])
return 1;
if(c1[i] < c2[i])
return -1;
}
void strcpy(char *d, const char *s){
int i = 0;
while(s[i] != '\0'){
d[i] = s[i];
i++;
}
d[i] = '\0';
}
String::~String(){
delete []ptr; //CRASHES HERE <-------------
}
String::String(){
ptr = new char[1];
ptr[0] = '\0';
}
String::String(const char *s){
int n = strlen(s);
ptr = new char(n+1);
strcpy(ptr, s);
}
String::String(const String& src){
int n = strlen(src.ptr);
ptr = new char(n+1);
strcpy(ptr, src.ptr);
}
int String::operator ==(const String& other){
return(strcmp(ptr, other.ptr) == 0);
}
int String::operator <(const String& other){
if(strcmp(ptr, other.ptr) == -1)
return 1;
else
return 0;
}
int String::operator >(const String& other){
if(strcmp(ptr, other.ptr) == 1)
return 1;
else
return 0;
}
void String::cpy(char* s){
delete []ptr;
int n = strlen(s);
ptr = new char[n + 1];
strcpy(ptr, s);
}
String& String::operator =(char* s){
cpy(s);
return *this;
}
String& String::operator=(String &src){
cpy(src.ptr);
return *this;
}
heres the call stack when it crashes
Code:
ntdll!TpWaitForAlpcCompletion ()
?? ()
ntdll!RtlLargeIntegerDivide ()
?? ()
ntdll!RtlCopyExtendedContext ()
?? ()
i know it shouldnt be my strcpy, strcmp, strlen functions because i tried it using the standard functions and no change.
another thing to note is that it only crashes when the String::String(const char *s); constructor is used.
thanks for any help. :confused: