memcpy problem
Oct 23, 2008 at 7:39am UTC
Hello,
The structure of my classes is :
String.h
1 2 3 4 5 6 7 8
class String
{
public :
String(char *);
~String();
private :
char * data;
}
String.cpp
1 2 3 4 5 6 7 8 9 10 11
#include "String.h"
String::String(char * data)
{
int datalength=sizeof (data); // shows 4 bytes
int stringdatalength=sizeof (String::data); // shows 4 bytes
int mul=STRLEN(data)*sizeof (char ); // shows 8 bytes
String::data=(char *)MALLOC(sizeof (String::data)+STRLEN(data)*sizeof (char ));
int newstringdatalength=sizeof (String::data); // shows 4 bytes
MEMCPY(String::data,data,sizeof (data));
}
Main.cpp
1 2 3 4 5 6
int main()
{
String x("abcd" ); // shows "abcd"
String y("abcdefghijk" ); // shows "abcd" instead of "abcdefghijk"
return 0;
}
While creating y object , the data pointer in the String class shows "abcd" instead of "abcdefghijk".
Now, logically String::data and data in the String constructor both shows it's respective size as 4 bytes.
checked out the memcpy API...it says n number of bytes are copied from source to destination.
However, it does not seem to happen here...what am i missing?
help appreciated
amal
Oct 23, 2008 at 6:41pm UTC
Why are you writing your own string class?
C++ has a string class already.
Oct 23, 2008 at 8:33pm UTC
You are confusing sizeof with strlen.
Look up strdup(), which will do what you want in 1 line of code.
Oct 24, 2008 at 5:57am UTC
1 2 3 4 5 6 7 8 9
String::String(char * data)
{
int datalength=sizeof (data);
int stringdatalength=sizeof (String::data); // ??
int mul=STRLEN(data)*sizeof (char ); // shows 8 bytes
String::data=(char *)MALLOC(sizeof (String::data)+STRLEN(data)*sizeof (char ));
int newstringdatalength=sizeof (String::data); // shows 4 bytes
MEMCPY(String::data,data,sizeof (data));
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Srtring::String() : data(NULL)
{
;
}
String::String(char * argData)
{
// copy 'data'
if ( argData != NULL )
{
data = new char [strlen(argData)+1];
strcpy( data, argData );
}
}
String::~String()
{
delete data;
}
general: avoid using C stuff when working with classes, use C++ new/delete
You need also a default ctor and an assignment op since you need this to do a "deep" copy. Also error handling should be in the code, i've left that out as well.
hth
Anders
Topic archived. No new replies allowed.