Set structure pointer to char * and copy

I have the following code

struct Info { int age; char name[5]; }
char buffer[20];
Info i;
i.age = 10;
sprintf(i.name, "Case");
strncpy(buffer+5, (char*)&i, sizeof(Info));

      

Now I want to restore the record

Info j;
strncpy((char*)&j, buffer+5, sizeof(Info));
printf("%d %s", j.age, j.name);

      

However, this prints an empty string for the name. I'm not sure what I am doing wrong.

+3


source to share


4 answers


There are two problems with your copy mechanism:

  • You are assuming it sizeof(Info)

    is 5. This is definitely not the case.
  • You are using strncpy

    which is for strings. Info

    is not a string, so you need to use memcpy

    .

The following will work:



char buffer[sizeof(i)];
memcpy(buffer, &i, sizeof(i));

...

memcpy(&j, buffer, sizeof(j));

      


There is another problem; name[5]

not big enough to hold "Casey"

like those 6 characters when you factor in the null terminator.

+6


source


There are several things:



  • You are overflowing the buffer, char name[5]

    cannot contain "Casey"

    , the terminator is invalid. This causes undefined behavior.
  • You copy from &i

    as if it were a pointer to a string, when in fact it is pointing to struct

    whose first field is int

    . It won't work reliably.
+4


source


There are several problems with the code you posted. First, the field is name

info

too short considering that "Casey" must be null terminated.

The observation you made has a different problem. The address j

will not be aligned with the field name

. This location is still there int age

, and most likely the field name

starts 4 bytes later, but that depends on your compiler.

As far as recovery goes age

, it won't work because it was never stored in the buffer.

What can happen if we assume it buffer

is large enough to store memcpy(buffer, &i, sizeof(Info))

and the first two arguments switched to restore. Usage sizeof

helps here because this way you tell the compiler how big the structure info

gets its way of arranging that structure in memory.

0


source


You don't need to use memcpy () to copy variables Info

. You can just use the assignment operator:

Info j;
j = i;
printf("%d %s", j.age, j.name);

      

You can do this because it Info

does not contain pointer member variables, and therefore you will get a deep copy when using the assignment operator. The same will happen if you just use the default copy constructor:

Info j(i);

      

or

Info j = i;

      

Of course, as pointed out by others, you have to make it Info::name

big enough to store the names you intend to store in it, including the line terminator '\0'

.

0


source







All Articles