c - memcpy for copying a fixed length buffer into a structure -


i have sample code:

struct {     char a[2];     char b[2]; } buff;  char buffer1[5] = "abcd"; 

to copy buffer1 structure members, doing this:

char c[3],d[3]; memcpy(&buff,buffer1,4); sprintf(c,"%2.2s",buff.a); sprintf(d,"%2.2s",buff.b); printf("c=%s,d=%s",c,d); 

when print variables c , d, getting values in c , d variable as: c="ab" , c="cd".

well question is, though getting output properly, memcpy affect related null character termination or have other unexpected memory-related consequences?

the 2 issues here:

1) mentioned in comments likely forget include space ending '\0' (i.e. nul in ascii) terminator character. %s format specifier printf function expects character string in valid form. nothing stops printing sequence of characters, here:

#include <stdio.h> #include <string.h>  struct {     char a[2];     char b[2]; } buff;  char buffer1[5] = "abcd";  int main(void) {     memcpy(&buff, buffer1, 4);      printf("first member: %c%c\n", buff.a[0], buff.a[1]);     printf("second member: %c%c\n", buff.b[0], buff.b[1]);      return 0; } 

2) more serious issue compiler may include arbitrary padding between struct members (as after last member), memcpy may not work expected. instead of copying (as may put bytes array unused "wholes"). suggest individual copies of each member or maybe using offsetof() macro.

from n1570 6.7.2.1/15 structure , union specifiers:

there may unnamed padding within structure object, not @ beginning.

and 6.7.2.1/17:

there may unnamed padding @ end of structure or union.

hence, should split memcpy 2 calls, instance:

memcpy(&buff.a, buffer1, 2); /* or replace 2 sizeof buff.a */ memcpy(&buff.b, buffer1+2, 2); 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -