Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

c - Overlapped memory casting a (void*) to a structure

On a project, I have a function using void pointer argument. In this function I cast the argument with a pointer to a defined structure. My problem is that my casted structure has overlapped memory location with other structures defined elsewhere. I guess this is due to the fact that when the void pointer is declared it only takes 1 byte but when it is casted it takes a lot more. Is there a solution to prevent casting to overlap memory location already used?

typedef struct ex_struct1
{
    unsigned char firstAttribut[10];
    unsigned char secondAttribut[10];
}ex_struct1_t;

typedef struct ex_struct2
{
    unsigned char some[11];
    unsigned char someother[11];
}ex_struct2_t;


void exempleFunction(void* myArg)
{
    ((ex_struct1_t*)myArg)->firstAttribut[0] = 1;
}


void main(void)
{
    unsigned char someBuffer[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
    ex_struct2_t ex_struct2;
    exempleFunction((void *)&someBuffer);
}

Exemple here :

myArg is located in 0x003CAD

I have another structure defined between 0x003CB2 and 0x003CC8

When i cast (ex_struct_t*)myArg it takes location between 0x003CAD and 0x003CC1

Hence, 0x0x003CB2 to 0x003CC1 are common to two declared structure and when one byte change in one of the structure it is applied in the other.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...