Feb
19

In embedded domain, Copying of structure is why avoided in c programming?

 

 

Generally  In embedded software domain for copying structure of same type people dont prefer to use direct assignment and do that by memcpy function or by doing assignment of each element of structure.

Look at Example

struct student {
int roll_no;
int age;
};
struct student exmple1 = {32,15};
struct student exmple2;

for copying exmple1 into exmple2.. instead of writing direct

exmple2=exmple1;

people like to use

memcpy(exmple2,exmple1,sizeof(struct student));

or

exmple2.roll_no=exmple1.roll_no;
exmple2.age=exmple1.age;
Why?


C has been used in embedded systems for many years, and early C compilers, before ANSI/ISO standardisation did not support direct structure assignment. see this post

Many practitioners are either from that era, or have been taught by those that were, or are using legacy code written by such practitioners.

This is probably the root of the doubt, but it is not a problem on an ISO compliant implementation.

On some very resource constrained targets, the available compiler(or tool chain for some specific platform) may not be fully ISO compliant for a number of reasons, so some people doubt that this feature would be affected so overcome from this problem they prefer to avoid the direct assignment of structure.

One more thing  is that when you assign a structure, an implementation need not duplicate the value of any undefined padding bits, therefore if you performed a structure assignment, and then performed a memcmp() rather than == to test for equality, there is no guarantee that they will be equal. However if you perform a memcpy(), any padding bits will be copied so that both memcmp() and == will yield equality.

So it is arguably safer to use memcmp() in all cases (not just embedded), but the improvement is marginal, and not conducive to readability. Better to stick to = and == or memcpy() and memcmp() and not mix the two.

 

 

JIGAR PATEL

hey I am an Artist who love to write code…! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here JigAr Patel

More PostsWebsiteTwitterFacebook

You may like to read this also....

Post comment

*

CommentLuv badge
Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

35 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link