• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

memcpy vs assignment in C

Under what circumstances should I expect memcpys to outperform assignments on modern INTEL/AMD hardware? I am using GCC 4.2.x on a 32 bit Intel platform (but am interested in 64 bit as well).

  • variable-assignment

Setjmp's user avatar

  • Interesting question! As you are obviously concerned on how to improve the speed of memory operations: Recently I read about the role of compression in memory transfer from someone developing pyTables: pytables.org/docs/StarvingCPUs.pdf As described there, the usual use of memcpy might be slow compared to his improvements with very fast compressors ( blosc ). Please regard this for high performance stuff only! –  math Mar 20, 2012 at 19:48
  • This question is quite broad. –  D. A. Sep 9, 2014 at 19:32

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?

Johannes Schaub - litb's user avatar

  • 4 Note that the reverse can apply - in GCC at least, memcpy of a small constant size is replaced with copy instructions, and if used with a pointer to a small source and/or destination does not prevent one or both being optimised into registers. So: do whatever results in the simplest code. –  Steve Jessop Nov 27, 2008 at 16:08
  • 4 You shouldn't expect one to outperform the other. If you have a performance problem, you should profile it, see if assignment/memcpy is the problem, and if so, try changing them to use the other, and see if that performs better. More profiling, less guesswork. ;) –  jalf Nov 27, 2008 at 16:10
  • 1 That is to say, I would expect "assignments will outperform memcpy" also to be false, given that the questioner has specified a recent GCC. But assuming no cast is required, I agree with your advice to use assignment, since it results in the clearest code. –  Steve Jessop Nov 27, 2008 at 16:11
  • @jalf: I totally agree. Since the question was "which is faster?", not "should I care which is faster?", I think "the compiler will deal with it whichever you do" is a fair answer, even though in the big picture the true answer is probably "why are you even asking?" ;-) –  Steve Jessop Nov 27, 2008 at 16:13
  • 5 Never say never... We had done some work on an embedded processor which uses a software unaligned exception handler. We found that structure assignment (using pointers) often caused unaligned exceptions, whereas memcpy did not. The cost of the exceptions was very high, so in the case where the memory was not necessarily aligned, memcpy was MUCH faster than assignment. –  John Oct 11, 2013 at 18:35

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged c struct variable-assignment memcpy or ask your own question .

  • The Overflow Blog
  • Fighting comment spam at Facebook scale (Ep. 602)
  • What it’s like being a professional workplace bestie (Ep. 603)
  • Featured on Meta
  • Moderation strike: Results of negotiations
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Discussions experiment launching on NLP Collective
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search

Hot Network Questions

  • Why do people say 'topless' but not 'topful'?
  • What does my wife want?
  • Was there a German embassy open in 1941 Lisbon?
  • Note to African American colleague - targeted crime
  • Typeclasses, traits, interfaces, protocols: is there any consistent terminology?
  • Confusion of what should be the object of a sentence
  • How do I select an array to loop through from an array of arrays?
  • What adhesive solution should use for walls with powdery surface?
  • What are Non-GNU versions of terminal commands?
  • Are heat sinks necessary for a Triac even in low current circuit?
  • NASA and the president's power
  • Pros and cons to round PCB design
  • Probability approximation and computation given Compound Poisson random variable
  • Estimate of Minkowski sum
  • Which airline is liable for compensation in case of missed connection?
  • Linux CLI tool for testing audio
  • Does Bayesianism give an out for pseudoscience that it shouldn’t deserve?
  • Congruences for power-sum of divisors
  • Do interspecies couples exist in Zootopia?
  • If Weird Al Yankovic Wrote Riddles
  • How to properly define volume for beginner calculus students?
  • What RPG had space travel, star gates, and an organization maybe called "Brothers of Battle"?
  • Are high-starch potatoes hard (low-starch soft)?
  • How does a Presta valve core work?

c assignment vs memcpy

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

memcpy versus assignment

  • Create Account

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,699 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.

c assignment vs memcpy

Structure assignment vs. memcpy/memmove?

Joe Schwartz's profile photo

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's profile photo

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

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

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()

Help Center Help Center

  • Help Center
  • Trial Software
  • Product Updates
  • Documentation

Use memcpy Function to Optimize Generated Code for Vector Assignments

You can use the Use memcpy for vector assignment parameter to optimize generated code for vector assignments by replacing for loops with memcpy function calls. The memcpy function is more efficient than for -loop controlled element assignment for large data sets. This optimization improves execution speed.

Selecting the Use memcpy for vector assignment parameter enables the associated parameter Memcpy threshold (bytes) , which allows you to specify the minimum array size in bytes for which memcpy function calls should replace for loops in the generated code. For more information, see Use memcpy for vector assignment and Memcpy threshold (bytes) . In considering whether to use this optimization,

Verify that your target supports the memcpy function.

Determine whether your model uses signal vector assignments (such as Y=expression ) to move large amounts of data, for example, using the Selector block.

To apply this optimization,

Consider first generating code without this optimization and measuring its execution speed, to establish a baseline for evaluating the optimized assignment.

Select Use memcpy for vector assignment and examine the setting of Memcpy threshold (bytes) , which by default specifies 64 bytes as the minimum array size for which memcpy function calls replace for loops. Based on the array sizes used in your application's signal vector assignments, and target environment considerations that might bear on the threshold selection, accept the default or specify another array size.

Generate code, and measure its execution speed against your baseline or previous iterations. Iterate on steps 2 and 3 until you achieve an optimal result.

The memcpy optimization may not occur under certain conditions, including when other optimizations have a higher precedence than the memcpy optimization, or when the generated code is originating from Target Language Compiler (TLC) code, such as a TLC file associated with an S-function block.

If you are licensed for Embedded Coder ® software, you can use a code replacement library (CRL) to provide your own custom implementation of the memcpy function to be used in generated model code. For more information, see Memory Function Code Replacement (Embedded Coder) .

Example Model

To examine the result of using the Use memcpy for vector assignment parameter on the generated vector assignment code, create a model that generates signal vector assignments. For example,

Use In , Out , and Selector blocks to create the following model.

c assignment vs memcpy

Open Model Explorer and configure the Signal Attributes for the In1 and In2 source blocks. For each, set Port dimensions to [1,100] , and set Data type to int32 . Apply the changes and save the model. In this example, the model has the name vectorassign .

For each Selector block, set the Index parameter to 1:50 . Set the Input port size parameter to 100 .

Generate Code

The Use memcpy for vector assignment parameter is on by default. To turn off the parameter, go to the Optimization pane and clear the Use memcpy for vector assignment parameter.

Go to the Code Generation > Report pane of the Configuration Parameters dialog box and select the Create code generation report parameter and the Open report automatically parameter. Then go to the Code Generation pane, select the Generate code only option, and generate code for the model. When code generation completes, the HTML code generation report is displayed.

In the HTML code generation report, click the vectorassign.c section and inspect the model step function. Notice that the vector assignments are implemented using for loops. /* Model step function */ void vectorassign_step(void) { int32_T i; for (i = 0; i < 50; i++) { /* Outport: '<Root>/Out1' incorporates: * Inport: '<Root>/In1' */ vectorassign_Y.Out1[i] = vectorassign_U.In1[i]; /* Outport: '<Root>/Out2' incorporates: * Inport: '<Root>/In2' */ vectorassign_Y.Out2[i] = vectorassign_U.In2[i]; } }

Generate Code with Optimization

Go to the Optimization pane of the Configuration Parameters dialog box and select the Use memcpy for vector assignment option. Leave the Memcpy threshold (bytes) option at its default setting of 64 . Apply the changes and regenerate code for the model. When code generation completes, the HTML code generation report again is displayed.

In the HTML code generation report, click the vectorassign.c section and inspect the model output function. Notice that the vector assignments now are implemented using memcpy function calls. /* Model step function */ void vectorassign_step(void) { /* Outport: '<Root>/Out1' incorporates: * Inport: '<Root>/In1' */ memcpy(&vectorassign_Y.Out1[0], &vectorassign_U.In1[0], 50U * sizeof(real_T)); /* Outport: '<Root>/Out2' incorporates: * Inport: '<Root>/In2' */ memcpy(&vectorassign_Y.Out2[0], &vectorassign_U.In2[0], 50U * sizeof(real_T)); }

Use memcpy for vector assignment

Related Topics

  • Design Techniques to Optimize Models for Efficient Code Generation
  • Vector Operation Optimization
  • Convert Data Copies to Pointer Assignments (Embedded Coder)

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

  • Switzerland (English)
  • Switzerland (Deutsch)
  • Switzerland (Français)
  • 中国 (English)

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

  • América Latina (Español)
  • Canada (English)
  • United States (English)
  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)

Contact your local office

  • | New Account
  • | Log In Remember [x]
  • | Forgot Password Login: [x]
  • Format For Printing
  •  -  XML
  •  -  Clone This Bug
  •  -  Top of page

IMAGES

  1. C Pointer

    c assignment vs memcpy

  2. What is the difference between memcpy memory copy and = direct

    c assignment vs memcpy

  3. STM32 malloc memory allocation failures

    c assignment vs memcpy

  4. C++ memcpy

    c assignment vs memcpy

  5. Memcpy Vs Memset For Zeroing A Struct In C [Duplicate] Top 16 Latest Posts

    c assignment vs memcpy

  6. How to use memcpy function in C language?

    c assignment vs memcpy

VIDEO

  1. Assignment operator in C language

  2. Compiler for C & C ++ #shortsfeed #shorts #viralvideo #viral #youtubeshorts #mingw #cprogramming

  3. CSE102 Programming Zero C Assignment Statement

  4. NPTEL Problem Solving Through Programming In C Week 0 Quiz Assignment Solution

  5. C# Beginners Tutorial

  6. C

COMMENTS

  1. What Is the Abbreviation for “assignment”?

    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.

  2. What Is a Deed of Assignment?

    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...

  3. What Is a Notice of Assignment?

    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...

  4. memcpy vs assignment in C

    The cost of the exceptions was very high, so in the case where the memory was not necessarily aligned, memcpy was MUCH faster than assignment. –

  5. memcpy() or assign? : r/C_Programming

    The assignment makes both val and ptr refer to the same object in memory, while memcpy() copies the bytes from one address (value of ptr) to

  6. C Language, memcpy versus assignment

    more efficient than using memcpy(), at leant on most modern ... using gcc on bcopy.c produces the following code: ... structures? memcpy vs. assignment?

  7. simple assignment of structs vs. memcpy

    simple assignment of structs vs. memcpy. C / C++ Forums on Bytes. ... aware of, there is no noticeable difference in performance, because

  8. Structure assignment vs. memcpy/memmove?

    As we all know, structures may contain "unnamed padding" between fields or at the end, to achieve the appropriate alignment (3.5.2.1).

  9. Structure Assignment and Its Pitfall in C Language

    The semantic meaning of = is an assignment, while memcpy just copies memory. That's a huge difference in readability as well

  10. memcpy performance issues

    rep movsb vs memcpy and memcpy showed best results on performance.

  11. Memcpy vs assignment in C

    Memcpy vs assignment in C. c++memcpystructvariable-assignment. Under what circumstances should I expect memcpys to outperform assignments on modern

  12. Copying structure in C with assignment instead of memcpy()

    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

  13. Use memcpy Function to Optimize Generated Code for Vector

    In the HTML code generation report, click the vectorassign.c section and inspect the model step function. Notice that the vector assignments are implemented

  14. Wrong optimization: padding in structs is not copied even with memcpy

    Note when changing struct s to say struct s { char c; ... SRA!) observe that RTL expansion copies padding for aggregate assignments: g: .