Thursday, February 11, 2010

A Coding Practise for Structure Assignment

Today I found one interesting thing :
This is in general can be a part of coding guidelines if we dont have.
NEVER USING = OPERATOR TO ASSIGN THE STRUCTURES. WE SHOULD RECOMMEND TO USE MEMCPY INSTEAD.
ex:
struct {
int rollNum;
name char[255];
} s1, s2;

Here lets suppose if we want to copy the data from s2 to s1 variable.
we can allways do
s1 = s2;
which is correct also.

But let us take an hypothetical scenario wherein we want to make this student structure into a member variable for another structure like
struct ScoreCard {
struct student s;
};
struct ScoreCard *pScoreCard;
pScoreCard = (struct ScoreCard *)malloc(sizeof(struct ScoreCard));
then (s1 = s2 ) kind of code breaks if we do as
pScoreCard->s = s2;

reason being pScoreCard is heap memory and it leads to SEGV.

Let us suppose coder wrote as (as per the new guideline)
memcpy(&s1, sizeof(struct student), &s2);
then there is mere change the the above one by prefixing the pointer

memcpy(pScoreCard->s1, sizeof(struct student), &s2).


Thats it.

No comments:

Post a Comment