Reputation: 13
the code bellow works ok if i comment the destructor and it print "Hello world" if not commented it print "Hello" only !! note i uses mingw 4.9 on windows xp 32bits and tha machine is very old pintume 4 1.8ghz
The strange thing about it is that this code works ok on other modern pc's , i only get this error on this old pc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct String{
public:
String(const char * txt){
len = strlen(txt);
if (len > 0)
buffer = (char*) malloc(len);
strcpy(buffer,txt);
}
void add(const char * txt){
realloc(buffer,len+strlen(txt));
strcpy(buffer+len,txt);
len += strlen(txt);
}
~String(){ if (len > 0) free(buffer);} // if commented it works fine !!!
char* get_ptr(){ return buffer;}
private:
char * buffer;
int len;
};
int main(){
String s("Hello");
s.add(" World");
printf(s.get_ptr());
getchar();
}
Upvotes: 0
Views: 38
Reputation: 40842
std::realoc has a return value, which returns the pointer to the reallocated memory area. This address can be the same as the input address, if there is enough free space behind the buffer, or can be a new address.
So if realloc(buffer,len+strlen(txt));
returns a pointer that is different to the one stored in buffer
then you will continue to work with an invalid pointer which results into undefined behavior. So for the PCs where it works, it might be because realloc
returns the same pointer, or just because the undefined behavior does result in the "correct" result.
Changing the code (adding/removing the code form the destructor) will result in different memory layout which also can result in different outcomes of the undefined behavior.
Regardless of this, realloc
is the wrong way to solve that problem in c++. You should use std::string
here (or maybe std::vector<char>
if don't want to have a string, but a buffer that you can resize).
Upvotes: 1