This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Issues with memcpy
- From: Brian Budge <brian dot budge at gmail dot com>
- To: Javier Valencia <jvalencia at log01 dot org>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Wed, 27 Apr 2005 14:49:06 +0200
- Subject: Re: Issues with memcpy
- References: <426F88EF.60904@log01.org>
- Reply-to: Brian Budge <brian dot budge at gmail dot com>
Could be my imagination, but are you assuming the size of your struct
is 9 bytes? This is most likely a false assumption. Try using
sizeof(t_st) instead. Likely it's 12 bytes.
Brian
On 4/27/05, Javier Valencia <jvalencia@log01.org> wrote:
> I'm having some issues with memcpy, i've attached two example files,
> just copying a structure in a char array. The result is different in
> both files, but they do the same.
>
> The output is this:
>
> tigre@enigma collector $ gcc pro.c
> tigre@enigma collector $ ./a.out
> 5 0 0 0 5 0 0 0 5
>
> tigre@enigma collector $ gcc pro2.c
> tigre@enigma collector $ ./a.out
> 5 fffffffa ffffffff ffffffbf 5 0 0 0 5
> 5 fffffffa ffffffff ffffffbf 5 0 0 0 5
>
> Can someone explain it to me?
>
> Thanks
>
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
>
> typedef struct
> {
> char ctype;
> int itype;
> int itype2;
> } t_st;
>
> int main()
> {
> int a;
> char buffer[9];
> t_st mystruct;
>
> mystruct.ctype = 5;
> mystruct.itype = 5;
> mystruct.itype2 = 5;
>
> bzero(buffer, 9);
>
> memcpy(buffer, (char*)&mystruct, 9);
>
> for(a=0; a<9; a++)
> printf("%x ", buffer[a]);
> printf("\n");
>
> return 0;
> }
>
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
>
> typedef struct
> {
> char ctype;
> int itype;
> int itype2;
> } t_st;
>
> int main()
> {
> int a;
> char buffer[9];
> char *buffer2;
> t_st mystruct;
>
> mystruct.ctype = 5;
> mystruct.itype = 5;
> mystruct.itype2 = 5;
>
> bzero(buffer, 9);
>
> memcpy(buffer, (char*)&mystruct, 9);
>
> for(a=0; a<9; a++)
> printf("%x ", buffer[a]);
> printf("\n");
>
> buffer2 = (char*)malloc(sizeof(char)*9);
> bzero(buffer2, 9);
>
> memcpy(buffer2, (char*)&mystruct, 9);
>
> for(a=0; a<9; a++)
> printf("%x ", buffer2[a]);
> printf("\n");
>
> return 0;
> }
>
>
>