Copying structure in C with assignment instead of memcpy()
c++ memcpy pointers struct
Up until recently, I have only seen copying of structure fields done with memcpy() . In classes and online instructions, copying the contents of one struct into another generally looks like
However, this task can also be accomplished by a simple assignment replacing the memcpy() .
Is there good reason why this isn't as widely used (at least in my limited experience)? Are these two methods—assignment and memcpy() —equivalent, or is there some compelling reason to use memcpy() in general?

Best Solution
Both methods are equivalent, and perform a shallow copy . This means that the structure itself is copied, but anything the structure references is not copied.
As for why memcpy is more popular, I'm not sure. Older versions of C did not support structure assignment ( although it was a common extension as early as 1978 ), so perhaps the memcpy style stuck as a way of making more portable code? In any case, structure assignment is widely supported in PC compilers, and using memcpy is more error-prone (if you get the size wrong, Bad Things are likely to happen), and so it's best to use structure assignment where possible.
There are, however, cases where only memcpy works. For example:
- If you're copying a structure to or from an unaligned buffer - eg, to save/load to/from disk or send/receive on a network - you need to use memcpy , as structure assignment requires both source and destination to be aligned properly.
- If you're packing additional information after a structure, perhaps using a zero-element array , you need to use memcpy , and factor this additional information into the size field.
- If you're copying an array of structures, it may be more efficient to do a single memcpy rather than looping and copying the structures individually. Then again, it may not. It's hard to say, memcpy implementations differ in their performance characteristics.
- Some embedded compilers might not support structure assignment. There's probably other more important things the compiler in question doesn't support as well, of course.
Note also that although in C memcpy and structure assignment are usually equivalent, in C++ memcpy and structure assignment are not equivalent. In general C++ it's best to avoid memcpy ing structures, as structure assignment can, and often is, overloaded to do additional things such as deep copies or reference count management.
Related Solutions
Memcpy vs assignment in c.
You should never expect them outperform assignments. The reason is, the compiler will use memcpy anyway when it thinks it would be faster (if you use optimize flags). If not and if the structure is reasonable small that it fits into registers, direct register manipulation could be used which wouldn't require any memory access at all.
GCC has special block-move patterns internally that figure out when to directly change registers / memory cells, or when to use the memcpy function. Note when assigning the struct, the compiler knows at compile time how big the move is going to be, so it can unroll small copies (do a move n-times in row instead of looping) for instance. Note -mno-memcpy :
Who knows it better when to use memcpy than the compiler itself?
How to initialize a struct in accordance with C programming language standards
In (ANSI) C99, you can use a designated initializer to initialize a structure:
Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." ( https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html )
Related Question
- Difference between a Structure and a Union
- With arrays, why is it the case that a[5] == 5[a]
- Memcpy() vs memmove()
memcpy versus assignment
A man is valued by his works, not his words!
Structure assignment and its pitfall in c language.
Jan 28 th , 2013 9:47 pm
There is a structure type defined as below:
If we want to assign map_t type variable struct2 to sturct1 , we usually have below 3 ways:
Consider above ways, most of programmer won’t use way #1, since it’s so stupid ways compare to other twos, only if we are defining an structure assignment function. So, what’s the difference between way #2 and way #3? And what’s the pitfall of the structure assignment once there is array or pointer member existed? Coming sections maybe helpful for your understanding.
The difference between ‘=’ straight assignment and memcpy
The struct1=struct2; notation is not only more concise , but also shorter and leaves more optimization opportunities to the compiler . The semantic meaning of = is an assignment, while memcpy just copies memory. That’s a huge difference in readability as well, although memcpy does the same in this case.
Copying by straight assignment is probably best, since it’s shorter, easier to read, and has a higher level of abstraction. Instead of saying (to the human reader of the code) “copy these bits from here to there”, and requiring the reader to think about the size argument to the copy, you’re just doing a straight assignment (“copy this value from here to here”). There can be no hesitation about whether or not the size is correct.
Consider that, above source code also has pitfall about the pointer alias, it will lead dangling pointer problem ( It will be introduced below section ). If we use straight structure assignment ‘=’ in C++, we can consider to overload the operator= function , that can dissolve the problem, and the structure assignment usage does not need to do any changes, but structure memcpy does not have such opportunity.
The pitfall of structure assignment:
Beware though, that copying structs that contain pointers to heap-allocated memory can be a bit dangerous, since by doing so you’re aliasing the pointer, and typically making it ambiguous who owns the pointer after the copying operation.
If the structures are of compatible types, yes, you can, with something like:
} The only thing you need to be aware of is that this is a shallow copy. In other words, if you have a char * pointing to a specific string, both structures will point to the same string.
And changing the contents of one of those string fields (the data that the char points to, not the char itself) will change the other as well. For these situations a “deep copy” is really the only choice, and that needs to go in a function. If you want a easy copy without having to manually do each field but with the added bonus of non-shallow string copies, use strdup:
This will copy the entire contents of the structure, then deep-copy the string, effectively giving a separate string to each structure. And, if your C implementation doesn’t have a strdup (it’s not part of the ISO standard), you have to allocate new memory for dest_struct pointer member, and copy the data to memory address.
Example of trap:
Below diagram illustrates above source memory layout, if there is a pointer field member, either the straight assignment or memcpy , that will be alias of pointer to point same address. For example, b.alias and c.alias both points to address of a.alias . Once one of them free the pointed address, it will cause another pointer as dangling pointer. It’s dangerous!!
- Recommend use straight assignment ‘=’ instead of memcpy.
- If structure has pointer or array member, please consider the pointer alias problem, it will lead dangling pointer once incorrect use. Better way is implement structure assignment function in C, and overload the operator= function in C++.
- stackoverflow.com: structure assignment or memcpy
- stackoverflow.com: assign one struct to another in C
- bytes.com: structures assignment
- wikipedia: struct in C programming language

Structure assignment vs. memcpy/memmove?

Joe Schwartz
(As an aside, is the Standard available in machine-readable format? I would love to be able to grep for stuff, like "padding".) -- Joe Schwartz E-mail: [email protected] or [email protected] MapInfo Corp. 200 Broadway These are my own opinions. Any similarity to the Troy, NY 12180 opinions of MapInfo Corporation is purely coincidental.
Henry Spencer
>(As an aside, is the Standard available in machine-readable
No. It's copyrighted (well, some doubts have been raised, but ANSI certainly *claims* copyright) and the publisher has opted to distribute only in hardcopy. -- Altruism is a fine motive, but if you | Henry Spencer @ U of Toronto Zoology want results, greed works much better. | [email protected] utzoo!henry

Forgot your password?
Please contact us if you have any trouble resetting your password.

Assignment vs Memcpy

Quote: Original post by ToohrVyk Very interesting, and it does make sense: the presence of a constructor marks the object as non-POD, so the compiler generates a member-wise assignment operator, which in turn incurs an alignment property.
Stephen M. Webb Professional Free Software Developer

This topic is closed to new replies.
Popular topics.

BadProgrammingGuide

Reticulating splines
- Create Account
Home Posts Topics Members FAQ
Join Bytes to post your question to a community of 472,958 software developers and data experts.
By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use .
To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.
[Solved]-memcpy vs assignment in C-C
you should never expect them outperform assignments. the reason is, the compiler will use memcpy anyway when it thinks it would be faster (if you use optimize flags). if not and if the structure is reasonable small that it fits into registers, direct register manipulation could be used which wouldn't require any memory access at all.
gcc has special block-move patterns internally that figure out when to directly change registers / memory cells, or when to use the memcpy function. note when assigning the struct, the compiler knows at compile time how big the move is going to be, so it can unroll small copies (do a move n-times in row instead of looping) for instance. note -mno-memcpy :
who knows it better when to use memcpy than the compiler itself?

Related Query
- memcpy fails but assignment doesn't on character pointers
- Exception thrown at 0x7C131F4C (ucrtbased.dll) in ICP LAB ASSIGNMENT PROJECT.exe: 0xC0000005
- Why does the compiler issue : warning: assignment makes integer from pointer without a cast
- One-line assignment of struct
- Long-form notation of a string assignment
- Segmentation fault in a list with memcpy
- assignment of arrays to pointers in C
- Error in assignment statement even when l-value given is fine in ternary operator
- C: Comparison between value initialization during definition & assignment after it
- How use memcpy to initialize array in struct
- Why do I get: "error: assignment to expression with array type"
- C dynamicaly changing size of array using malloc and memcpy
- How the assignment statement in an if statement serves as a condition?
- converting string to ascii and error assignment to expression with array type
- memcpy to concat smaller arrays into bigger ones
- Assignment from void pointer to another void pointer
- Is memcpy of array in C Vaxocentrist?
- Converting an array to pointer for memcpy
- Accessing Struct members using memcpy in C
- C pointer changes without assignment
- char array assignment using two indexes added together
- Using addressof with memcpy of 2 arrays
- Assignment with two values in Linux kernel
- Segmentation Fault while using memcpy in C
- lvalue required as left operand of assignment in some old c code
- C Assignment Arrays Error
- 2D array assignment using a for loop
- assignment makes pointer from integer without a cast
- How the assignment operator in container_of() macro is working
- NEON simple vector assignment intrinsic?
More Query from same tag
- MISRA: Bitwise operation on signed integer
- C float from binary
- C unrelated function seems to affect simple array initialization
- How to declare a lua_CFunction that takes a single function argument on the stack?
- C: bit operations on a variable-length bit string
- Accessing data from an address
- TCP write() prints char* to itself rather than to buffer only on first socket connection, but works OK on second connection onwards
- Vim Shortcuts or plug-ins for the following
- How to find minimal and maximal address of dll
- C arguments from the C primer plus 6e should effect print
- Why am i getting EXC_BAD_ACCESS (code=1, address=0x0)?
- Turn each line of a text file into an array c
- Should I count the required amount of memory before allocating?
- Using 'char' variables in bit operations
- Why *c++ increasing pointer value but not the ascii of first Char?
- Get Min and Max label in from the array loop
- Where is 2 dimensional array's size and how to use point to make 1 dimensional to 2?
- Finding the average, maximum, minimum value of array in c
- In solaris vsnprintf core dump in strlen function is any method to resolve this?
- MSVC where in-built data types and functions are defined
- How do I initialize a struct containing another struct?
- Return structure pointer in C
- snprintf printing giberish on microcontroller, but is fine in other environments
- How best to alleviate scenarios that trigger non-incremental linking (MSVS)
- Using a library written in C with C++
- Trying to automate git, commit only called "T"
- C: Best Practise passing information from function to calling routine
- Debug error selection sort
- Second return type in function declaration?
- Printing a multi-dimensional array with additional rows and columns
Copyright 2023 www.appsloveworld.com . All rights reserved.

IMAGES
VIDEO
COMMENTS
According to Purdue University’s website, the abbreviation for the word “assignment” is ASSG. This is listed as a standard abbreviation within the field of information technology.
In real property transactions, a deed of assignment is a legal document that transfers the interest of the owner of that interest to the person to whom it is assigned, the assignee. When ownership is transferred, the deed of assignment show...
A Notice of Assignment is the transfer of one’s property or rights to another individual or business. Depending on the type of assignment involved, the notice does not necessarily have to be in writing, but a contract outlining the terms of...
We found that structure assignment (using pointers) often caused unaligned exceptions, whereas memcpy did not. The cost of the exceptions was
I personally use memcpy() explicitly for structs too, instead of assignment. The idea behind that is that C is not C++: in C, we're not
You may be able to
You should never expect them outperform assignments. The reason is, the compiler will use memcpy anyway when it thinks it would be
D. Chadwick Gibbo #1 / 7. memcpy versus assignment. In several books I've seen that assignment of structures is usually more efficient than using memcpy(), at
The semantic meaning of = is an assignment, while memcpy just copies memory. That's a huge difference in readability as well, although memcpy
As we all know, structures may contain "unnamed padding" between fields or at the end, to achieve the appropriate alignment (3.5.2.1).
will inline and optimise small memcpy()s. ... memcpy(), because it flags "here is a potentially long operation". -- Free games and programming
Hello, i 'd like to share a performance observation i made about the following code: #include <iostream> #define UInt8 unsigned char
Simply assign one object to another with the assignment operator. Structure assignments have been supported since C90. ... to another, then you'll
you should never expect them outperform assignments. the reason is, the compiler will use memcpy anyway when it thinks it