Weird error

Pages: 12
a class which has only data, memcpy will only overwrite data only. lets say we talk about a normal string class which will ba around 8 bytes something like this:

1
2
3
4
5
class string
{
int length;
char *ptr;
};


now if you memcpy this will overwrite @length or might be the @ptr. even if they are not set properly, this will not lead to a crash.
it will only crash if you do memcpy improperly like you bypass the object size.
Thanks a lot for the reply guys!
Ugh, no.

Ok, writeonsharma, try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <assert.h>
#include <string>
#include <string.h>
#include <iostream>

using namespace std;

class str {
  public:  
  int length;
  char* ptr;
};

struct foo {
   int x, y;
};

int main() {
  assert( sizeof( foo ) == sizeof( str ) );
  foo f;
  f.x = 10;
  f.y = 20;
  str s;
  memcpy( &s, &f, sizeof( s ) );
  *(s.ptr) = 4;    // SEGV right here
  cout << "Never gets here" << endl;
}


EDIT: And then consider that the STL string implementation contains pointers in it as well.
Last edited on
hehehe...this you will get without any memcpy or memset also. right?

second thing.. this will over write the address of s.ptr and not value.. it is going to give segv fault..no doubt.

see i never said doing memcpy on struct of class will never fault.. i said if you do it properly you can accomplish what you want. understand my point.. memcpy will just over write the values..im not talking about virtual classes!!

and you also must have done something like this alot often:

1
2
3
4
5
6
7
typedef struct x
{
...some data...
}x;

x xobj;
memset(&xobj, 0, sizeof(x));


right?? and i dont think struct and class are very different!!
what you are saying is right but what im saying is also correct to some extent.. :D
I _never_ use memcpy or memset.

I write default constructors when the compiler-supplied default is not sufficient. I write copy constructors and assignment operators when the compiler-provided ones are not sufficient.

(Also typedef struct foo { } foo; is absolutely braindead in C++.)

I guess I don't understand what you are saying to know whether what you are saying is correct. But I do know that when using C++, memcpy/memset really should not be used even on simple value classes/structs; constructors should be used instead.
hmmm...

lets leave this discussion here and look for other interesting problems in the forum... :)
Topic archived. No new replies allowed.
Pages: 12