I've got a structure like this:
struct st {
int a;
int b;
int c; } x;
If I do the following:
memcpy(dst, (char *) &x.b, 8);
I get an execption at runtime:
Unhandled exception: ECALL, data: 0x00000000
Why is that?
Why do I get an exception when trying to memcpy a section of Topic is solved
-
- Experienced Member
- Posts: 104
- Joined: Fri Dec 11, 2009 8:29 pm
-
- Experienced Member
- Posts: 104
- Joined: Fri Dec 11, 2009 8:29 pm
The exception is due to the safe pointer bounds checks in xC.
In xC if you take a safe pointer to a structure member then the bounds on that pointer allow you to only access that member.
If you want to manipulate the memory of a structure you have to take a pointer to the whole structure - not just a member e.g.
struct st x;
char * p = &x;
In the example above you want to do something like:
memcpy(dst, ((char *) &x) + 4, 8);
Of course, this code means you know how the struct is laid out in memory. A useful macro is this:
#define struct_offset(s, x) ((char *) &s.x - (char *) &s)
This means you could write:
memcpy(dst, ((char *) &x) + struct_offset(x, b), 8);
This code is more explicit that it wants to treat the struct as a block of characters in memory.
In xC if you take a safe pointer to a structure member then the bounds on that pointer allow you to only access that member.
If you want to manipulate the memory of a structure you have to take a pointer to the whole structure - not just a member e.g.
struct st x;
char * p = &x;
In the example above you want to do something like:
memcpy(dst, ((char *) &x) + 4, 8);
Of course, this code means you know how the struct is laid out in memory. A useful macro is this:
#define struct_offset(s, x) ((char *) &s.x - (char *) &s)
This means you could write:
memcpy(dst, ((char *) &x) + struct_offset(x, b), 8);
This code is more explicit that it wants to treat the struct as a block of characters in memory.