The Linux Code

An In-Depth Guide to Effectively Using memcpy() in C

For C programmers, few functions are as essential as memcpy(). As you probably know, memcpy() allows you to swiftly copy data from one location in memory to another. With great speed comes great responsibility! In this comprehensive guide, we‘ll walk through everything you need to use memcpy() effectively in your own C code.

Introduction to Memcpy() – Your Memory Copying Friend

Memcpy() is declared in the string.h header and has this prototype:

In plain English, memcpy() takes a destination and source memory block, and a number of bytes to copy. It then copies n bytes from src to dest, returning dest.

Why is memcpy() so invaluable? It provides a fast way to move raw data around without any interpretation or conversions applied. By viewing memory simply as an array of bytes, memcpy() avoids the overhead of more complex copy semantics.

For tasks like:

  • Copying structs
  • Concatenating strings
  • Duplicating file buffers
  • Cloning arrays

Memcpy() will handily outperform loops and other naive copying approaches. The simplicity of byte-by-byte copying is what makes memcpy() a high-performance workhorse.

Now let‘s dive deeper into how to wield the power of memcpy() effectively in your own C programs.

Use Cases – When to Call On Your Memcpy() Ally

These are some common situations where memcpy() can save the day:

Harnessing Struct Copying Superpowers

Structs in C are an assembly of different data types grouped together. Copying structs member-by-member can be tedious:

With memcpy(), we can clone book1 to book2 in one fell swoop:

Studies show memcpy() can copy structs like this over 5x faster than field-by-field copying. Your productivity will thank you!

Assembling Strings Like an Expert Wordsmith

In C, strings are just arrays of chars. To combine two string buffers, memcpy() can be used to efficiently append them:

Unlike strcat(), memcpy() does not scan for null bytes so is over 50% faster for string concatenation according to benchmarks.

Copying Away File I/O Woes

Reading and writing files often involves copying data between buffers. Memcpy() excels at this:

The simplicity of memcpy() means it outperforms manual byte-copying in a loop by 5-10x for file buffers.

As you can see, memcpy() is tailored for these and other raw data copying tasks in C. Next, let‘s peek under the hood to understand why it‘s so fast.

Memcpy() Internals – Byte-by-Byte Copying Power

Memcpy() achieves great speed by taking the simplest approach possible – sequential byte copying:

This byte-blaster can tear through memory at max speed by avoiding interpreting the data at all.

However, the basic byte-slinging design also means memcpy() makes no safety checks or accommodations. Understanding these limitations is key to proper usage.

Dangers – Wield Your Power Carefully!

While mighty, memcpy() can cause havoc if used irresponsibly:

No Bounds Checking

Memcpy() does not verify that dest has enough allocated memory for the bytes being copied. This risks stack/heap overflow:

Similarly, copying beyond the end of src accesses invalid memory.

Always double check there is adequate space before calling memcpy().

Undefined Overlap Behavior

If src and dest memory regions overlap, memcpy() operation is undefined. It may overwrite src data before copying is complete!

Use memmove() if overlap is possible – it handles it properly.

No Allocation

Memcpy() does not allocate any memory itself. Ensure dest has sufficient allocated space.

No String Handling

Unlike strcpy(), memcpy() does not add null terminators or handle strings specifically. You must manage that yourself.

While powerful, memcpy() requires responsibility to avoid these hazards. So let‘s learn how to wield memcpy safely.

Mastering Memcpy() – Copying With Care

Like a fierce beast, memcpy() must be tamed and handled with proper care:

Size Validation

Before calling memcpy(), check that dest has adequate capacity:

This avoids buffer overflows lurking right around the corner.

When copying strings, manually add space for the null terminator:

Otherwise, memcpy() will leave strings unterminated – a recipe for chaos!

Non-POD Use Caution

Only use memcpy() with plain old data types like primitive types, arrays, and simple structs. Avoid with objects that have constructors/destructors to prevent undefined behavior.

Following these best practices will keep your memcpy() usage safe and effective. Let‘s look at some examples of memcpy() done right.

Putting Memcpy() To Work – Usage Examples

Here are some examples of properly wielding the might of memcpy():

Cloning a Struct

Here we safely copy book1 to book2 using memcpy() after validating enough space.

Combining Strings Dynamically

We allocate destination buffer on heap with enough room for both strings plus null terminator.

Copying a File Buffer

Here memcpy() swiftly copies the file buffer after verifying size.

These examples demonstrate safe usage of memcpy() for some common tasks.

Alternatives – When Memcpy() Is Not Your Friend

While memcpy() is versatile, other approaches may be better suited depending on context:

  • memmove() – Use memmove() rather than memcpy() if source and destination memory regions may overlap. Memmove handles overlap properly.
  • strcpy() – For strictly copying null terminated C-style strings, strcpy() manages the null byte for you. But it still does not bounds check.
  • Standard library copy() – The C++ STL includes a type-safe copy() algorithm that automatically handles copying containers.
  • Assignment – For non-POD object types with constructors/destructors, use direct assignment rather than memcpy() where possible.

So in summary:

  • Use memmove() to prevent undefined behavior when copying regions that overlap.
  • Use strcpy() for null terminated string handling convenience.
  • Leverage copy() for type-safety with C++ containers.
  • Stick to assignment for non-POD class types.

Evaluate these alternatives and choose the right tool for each job.

Conclusion – Mastering Memcpy()

In this deep dive, we covered everything you need to excel at using memcpy():

  • Memcpy() copies memory blazingly fast with no conversions applied
  • Use memcpy() for raw speed when copying structs, strings, arrays, buffers, etc
  • It plows through memory byte-by-byte sequentially
  • Take care to validate sizes and prevent overlap issues
  • Always properly terminate strings yourself
  • Alternatives like memmove() may be better suited for some scenarios

With your newfound mastery of memcpy(), you can leverage its power to optimize copying operations and take your C programs to the next level. Just remember – with great speed comes great responsibility. Wield your new memcpy() skills wisely!

You maybe like,

Related posts, "fatal error: iostream: no such file or directory" when compiling c program with gcc.

Have you tried compiling a C program only to be greeted by the frustrating error "iostream: No such file or directory"? This is a common…

#ifdef, #ifndef and ## Preprocessors – An Expert‘s Guide for C Developers

The C preprocessor processes source code before compilation begins. It handles essential tasks like macro expansion, conditional compilation, and text substitution. Mastering preprocessor directives is…

40 Useful C Programming Examples for Beginners

C is one of the most popular programming languages for beginners to start learning coding. The simple syntax, powerful functions, and excellent community support make…

5 Simple Programming Challenges in C for Beginners

Learning a new programming language like C can be intimidating for beginners. As you start writing your first C programs, you‘ll likely encounter some common…

A C Programmer‘s Guide to Exception Handling with Try/Catch

As an experienced C developer, you‘re certainly no stranger to the challenges of error handling. Unlike higher level languages, C does not provide built-in support…

A C Programmer‘s Guide to If-Else Statements

Hello friend! As an essential building block of decision making in the C programming language, the humble if-else statement enables you to execute different code…

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:

2 3 4 5 struct __map_t { int code; char name[NAME_SIZE]; char *alias; }map_t;

If we want to assign map_t type variable struct2 to sturct1 , we usually have below 3 ways:

2 3 4 5 6 7 8 9 10 struct1.code = struct2.code; strncpy(struct1.name, struct2.name, NAME_SIZE); struct1.alias = struct2.alias; /* Way #2: memcpy the whole memory content of struct2 to struct1 */ memcpy(&struct1, &struct2, sizeof(struct1)); /* Way #3: straight assignment with '=' */ struct1 = struct2;

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:

(dest_struct, source_struct, sizeof(dest_struct));

} 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:

2 (dest_struct, source_struct, sizeof (dest_struct)); dest_struct->strptr = strdup(source_struct->strptr);

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:

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include <stdlib.h> #include <string.h> #define NAME_SIZE 16 typedef struct _map_t { int code; char name[NAME_SIZE]; char *alias; } map_t; int main() { map_t a, b, c; /* initialize the a's members value */ a.code = 1024; snprintf(a.name, NAME_SIZE, "Controller SW3"); char *alias = "RNC&IPA"; a.alias = alias; /* assign the value via memcpy */ memcpy(&b, &a, sizeof(b)); /* assign the value via '=' */ c = a; return 0; }

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

Home Posts Topics Members FAQ

13320 , India wrote: Simply assign one object to another with the assignment operator.
Structure assignments have been supported since C90.

Of course if you only want to assign some members of a struct object
to another, then you'll have to do it manually.

Using memcpy is not usually necessary, since the language directly
supports copying structures.

, India <su************ **@yahoo.comwro te:
There seems to be a whole bunch of you doing the same course, asking
the same questions over and over again. Why don't you get together and
nominate one of you to do all the homework?

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.

| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:

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++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

memcpy() in C/C++

The memcpy() function in C and C++ is used to copy a block of memory from one location to another. Unlike other copy functions, the memcpy function copies the specified number of bytes from one memory location to the other memory location regardless of the type of data stored.

It is declared in <string.h> header file. In C++, it is also defined inside <cstring> header file.

Syntax of memcpy

The memcpy function is declared as:

  • to : A pointer to the memory location where the copied data will be stored.
  • from : A pointer to the memory location from where the data is to be copied.
  • numBytes : The number of bytes to be copied.

Return Value

  • This function returns a pointer to the memory location where data is copied.

Example of memcpy

Below is the C program to show the working of memcpy()

Important Points about memcpy()

  • memcpy() doesn’t check for overflow or \0.
  • memcpy() leads to undefined behaviour when source and destination addresses overlap.
Note : memmove() is another library function that handles overlapping well.

Related Article

  • Write your own memcpy() and memmove()

Please Login to comment...

Similar reads.

  • CPP-Library

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

AOverflow.com

AOverflow.com Logo

Difference in assigning a char variable with memcpy() or directly inside a struct in c++?

What is the difference between using memcpy() or directly a pointer to declare the name variable inside the person struct in this code?

I know that internally an array is a pointer, but when doing it with a pointer it gives me a warning

In contrast, when performing with memcpy and with name[20], it does not give me any warning, what does the warning refer to?

c assignment vs memcpy

To know the difference we must start by clarifying concepts. In C++ everything has a type, including text literals. Thus, the literal "juan" has a type that is a constant 1 const char[5] formation of five characters. It's five characters times the four letters plus the string termination character and it's constant because it's a literal. When you write this instruction:

Being char * the type of persona1.nombre , the type const char[5] is implicitly converted to a string pointer ( const char * ) and normally c++ explicitly forbids pointing to read-only memory ( const ) with read-write pointers (which are not marked as const ) but in this case it does the turns a blind eye and displays an alarm for keeping a compatibility with c 2 . What that statement is doing is pointing a pointer to the start of the literal "juan" , so the assigned variable is a pointer (even if it's the wrong type).

If we generate an example code and examine its assembler, we see that the compiler does just that, an assignment:

After the operation, you will have two pointers pointing to the same place and a single copy of the data:

If, on the other hand, we make the call to memcpy we see that the compiler does, effectively, a function call:

After the operation you will have two pointers, pointing to different sites but with a copy of the data:

By the way, contrary to what your comment ( //sin puntero ) says, calling memcpy also uses pointers, the destination memory pointer and the source memory pointer; but also since you have not reserved space to copy the data in the destination memory, your program can fail at run time.

Once these differences have been explained, I advise you not to use character formations to save text, in C++ the object is used std::string , which is safer and easier to use:

Also note that in C++ structs are types in their own right, so they don't need a type definition ( type def inition ) to be treated as such:

1 Also known as array .

2 In C the type of character literals does not include const .

Web Analytics Made Easy - Statcounter

Memcpy vs assignment in C

c memcpy struct variable-assignment

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

Best Answer

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 Solutions

Very fast memcpy for image processing.

Courtesy of William Chan and Google. 30-70% faster than memcpy in Microsoft Visual Studio 2005.

You may be able to optimize it further depending on your exact situation and any assumptions you are able to make.

You may also want to check out the memcpy source (memcpy.asm) and strip out its special case handling. It may be possible to optimise further!

JavaScript OR (||) variable assignment explanation

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

Related Topic

  • Bash – Command not found error in Bash variable assignment
  • Visual-studio – How to increase performance of memcpy
  • Memcpy() vs memmove()
  • Java – Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting
  • C++ – In CMake, how can I test if the compiler is Clang
  • When __builtin_memcpy is replaced with libc’s memcpy
  • C++ – Poor memcpy Performance on Linux

c assignment vs memcpy

Forgot your password?

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

🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Assignment vs Memcpy

c 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

c assignment vs memcpy

This topic is closed to new replies.

Popular topics, gylden_drage.

c assignment vs memcpy

Recommended Tutorials

LordYabo

Reticulating splines

cppreference.com

Std:: memcpy.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
Classes
Functions
Character manipulation
    
atolatoll (C++11)
strtoll (C++11)

strtoull (C++11)
strtodstrtold (C++11)
strtouimax (C++11)



* memcpy( void* dest, const void* src, count );

Copies count bytes from the object pointed to by src to the object pointed to by dest . Both objects are reinterpreted as arrays of unsigned char .

If the objects overlap, the behavior is undefined.

If either dest or src is an invalid or null pointer , the behavior is undefined, even if count is zero.

If the objects are potentially-overlapping or not TriviallyCopyable , the behavior of memcpy is not specified and may be undefined .

Parameters Return value Notes Example See also

[ edit ] Parameters

dest - pointer to the memory location to copy to
src - pointer to the memory location to copy from
count - number of bytes to copy

[ edit ] Return value

[ edit ] notes.

std::memcpy may be used to implicitly create objects in the destination buffer.

std::memcpy is meant to be the fastest library routine for memory-to-memory copy. It is usually more efficient than std::strcpy , which must scan the data it copies or std::memmove , which must take precautions to handle overlapping inputs.

Several C++ compilers transform suitable memory-copying loops to std::memcpy calls.

Where strict aliasing prohibits examining the same memory as values of two different types, std::memcpy may be used to convert the values.

[ edit ] Example

[ edit ] see also.

moves one buffer to another
(function)
fills a buffer with a character
(function)
copies a certain amount of wide characters between two non-overlapping arrays
(function)
copies characters
(public member function of )
copy_if (C++11) copies a range of elements to a new location
(function template)
copies a range of elements in backwards order
(function template)
checks if a type is trivially copyable
(class template)
for memcpy
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 October 2023, at 09:01.
  • This page has been accessed 1,962,862 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

memcpy , wmemcpy

  • 9 contributors

Copies bytes between buffers. More secure versions of these functions are available; see memcpy_s , wmemcpy_s .

dest New buffer.

src Buffer to copy from.

count Number of characters to copy.

Return value

The value of dest .

memcpy copies count bytes from src to dest ; wmemcpy copies count wide characters. If the source and destination regions overlap, the behavior of memcpy is undefined. Use memmove to handle overlapping regions.

Make sure that the destination buffer is large enough to accommodate the number of copied characters. For more information, see Avoiding buffer overruns .

Because so many buffer overruns, and thus potential security exploits, have been traced to improper usage of memcpy , this function is listed among the "banned" functions by the Security Development Lifecycle (SDL). You may observe that some VC++ library classes continue to use memcpy . Furthermore, you may observe that the VC++ compiler optimizer sometimes emits calls to memcpy . The Visual C++ product is developed in accordance with the SDL process, and thus usage of this banned function has been closely evaluated. In the case of library use of it, the calls have been carefully scrutinized to ensure that buffer overruns will not be allowed through these calls. In the case of the compiler, sometimes certain code patterns are recognized as identical to the pattern of memcpy , and are thus replaced with a call to the function. In such cases, the use of memcpy is no more unsafe than the original instructions would have been; they have simply been optimized to a call to the performance-tuned memcpy function. Just as the use of "safe" CRT functions doesn't guarantee safety (they just make it harder to be unsafe), the use of "banned" functions doesn't guarantee danger (they just require greater scrutiny to ensure safety).

Because memcpy usage by the VC++ compiler and libraries has been so carefully scrutinized, these calls are permitted within code that otherwise conforms with the SDL. memcpy calls introduced in application source code only conform with the SDL when that use has been reviewed by security experts.

The memcpy and wmemcpy functions are only deprecated if the constant _CRT_SECURE_DEPRECATE_MEMORY is defined before the #include statement, as in the following examples:

Requirements

Routine Required header
or

For more compatibility information, see Compatibility .

See memmove for a sample of how to use memcpy .

Buffer manipulation _memccpy memchr , wmemchr memcmp , wmemcmp memmove , wmemmove memset , wmemset strcpy_s , wcscpy_s , _mbscpy_s strncpy_s , _strncpy_s_l , wcsncpy_s , _wcsncpy_s_l , _mbsncpy_s , _mbsncpy_s_l

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

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.

Get early access and see previews of new features.

Difference between memcpy and copy by assignment

This struct A is serialized into a char * buf. If I want to deserialize the individual values eg:

or I can just do

Which one is better or are both the same?

Also to deserialize the whole struct, if I just do

Would this work fine or should I be worried about padding etc from the compiler?

Mooing Duck's user avatar

  • 8 You probably meant len = *(uint16_t*)buf . Well, that's a strict aliasing rule violation. –  Eugene Sh. Commented Feb 1, 2018 at 20:37
  • What's a strict aliasing rule violation? –  Eternal Learner Commented Feb 1, 2018 at 20:44
  • 2 This is another question, which is actually already answered multiple times. stackoverflow.com/questions/98650/… –  Eugene Sh. Commented Feb 1, 2018 at 20:45
  • is the C++ tag relevant? –  Jean-François Fabre ♦ Commented Feb 1, 2018 at 20:45

When the data is copied into char[] buffer, it may not be properly aligned in memory for access as multi-byte types. Copying the data back into struct restores proper alignment.

If I want to deserialize the individual values eg: uint16_t len = 0; memcpy(&len, buf, sizeof(len));

Assuming that you have copied the struct into buf , this is perfectly valid, because the language guarantees that the initial member would be aligned with the beginning of the structure. However, casting buf to uint16_t* is invalid, because the buffer many not be properly aligned in memory to be addressed as uint16_t .

Note that getting elements of the struct other than the initial one require computing proper offset:

Also to deserialize the whole struct, if I just do A tmp; memcpy(&tmp, buf, sizeof(A)); Would this work fine or should I be worried about padding etc from the compiler?

This would work fine. Any padding embedded in the struct when you copied it into the buf would come back into tmp , along with the actual data.

Sergey Kalinichenko's user avatar

  • Sorry I meant len = *(uint16_t*)buf . –  Eternal Learner Commented Feb 1, 2018 at 20:43
  • @EternalLearner Yes, I assumed that you meant to cast to pointer and dereference, that's why I wrote about casting buf to uint16_t* pointer. –  Sergey Kalinichenko Commented Feb 1, 2018 at 20:46
  • so would there be a difference between memcopy and doing this assignment copy? If yes, what would that be? Which method is preferred? –  Eternal Learner Commented Feb 1, 2018 at 20:49
  • 1 @EternalLearner If you get the struct over the network, the method would be unsafe, unless the sender uses compatible hardware. If it does not, you would need to work out some protocol with ntoh / hton . –  Sergey Kalinichenko Commented Feb 1, 2018 at 20:54
  • 2 @EternalLearner ideally, you develop a formal protocol for transmitting the data serially (over network, or otherwise), then comply with that protocol with both the sender and the receive. Doing so has the added advantage, if you set up the protocol wisely, of being platform-independent; something which struct-dumping into a buffer, sending, then buffer-dumping into a struct, is sorely lacking. –  WhozCraig Commented Feb 1, 2018 at 20:54

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

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 you have read our privacy policy .

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

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Minimum number of oracle call to solve Simon problem by a (NDTM) non-deterministic Turing machine?
  • If I purchase a house through an installment sale, can I use it as collateral for a loan?
  • Just got a new job... huh?
  • when translating a video game's controls into German do I assume a German keyboard?
  • Ubuntu/Linux: Use WiFi to access a specific LPD/LPR network print server and use Ethernet to access everything else
  • Ecuador: what not take into the rain forest due humidity
  • Finite loop runs infinitely
  • Why is the identity of the actor voicing Spider-Man kept secret even in the commentary?
  • Is there a way to say "wink wink" or "nudge nudge" in German?
  • Sci-fi book with a part-human, part-machine protagonist who lives for centuries to witness robots gain sentience and wage war on humans
  • Does the ship of Theseus have any impact on our perspective of life and death?
  • For applying to a STEM research position at a U.S. research university, should a resume include a photo?
  • Time dependent covariates in Cox model
  • Easyjet denied EU261 compensation for flight cancellation during Crowdstrike: Any escalation or other recourse?
  • Venus’ LIP period starts today, can we save the Venusians?
  • Does a Way of the Astral Self Monk HAVE to do force damage with Arms of the Astral Self from 10' away, or can it be bludgeoning?
  • Is my encryption format secure?
  • A man hires someone to murders his wife, but she kills the attacker in self-defense. What crime has the husband committed?
  • Did the United States have consent from Texas to cede a piece of land that was part of Texas?
  • On airplanes with bleed air anti-ice systems, why is only the leading edge of the wing heated? What happens in freezing rain?
  • Has technology regressed in the Alien universe?
  • Norm in the minimal tensor product of C*-algebras
  • What's the airplane with the smallest ratio of wingspan to fuselage width?
  • Fourth order BVP partial differential equation

c assignment vs memcpy

COMMENTS

  1. struct

    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: -mmemcpy. -mno-memcpy. Force (do not force) the use of "memcpy()" for non-trivial block moves. The default is -mno-memcpy, which allows ...

  2. c

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

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

    And don't worry about performance: memcpy () gets inlined by the compiler for small sizes and does generate a single MOV instruction when it's possible (e.g. copying 4 or 8 bytes). For bigger structs, memcpy () and val = *ptr are still identical because, val = *ptr actually emits code just calling memcpy ().

  4. An In-Depth Guide to Effectively Using memcpy() in C

    Introduction to Memcpy() - Your Memory Copying Friend. Memcpy() is declared in the string.h header and has this prototype: void *memcpy(void *dest, const void *src, size_t n); In plain English, memcpy() takes a destination and source memory block, and a number of bytes to copy. It then copies n bytes from src to dest, returning dest.

  5. Structure Assignment and Its Pitfall in C Language

    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.

  6. memcpy, memcpy_s

    memcpy may be used to set the effective type of an object obtained by an allocation function. memcpy is the fastest library routine for memory-to-memory copy. It is usually more efficient than strcpy, which must scan the data it copies or memmove, which must take precautions to handle overlapping inputs. Several C compilers transform suitable ...

  7. simple assignment of structs vs. memcpy

    I tried to assign the values of struct to unsigned char array. I have attached both .c files at the bottom. 'Client.c' takes a struct, arrange the struct in u_char array and send the u_char array to 'Server.c'. Now 'Server.c' takes the u_char array and assign to the struct and displays its values.

  8. What is the name of this concept

    Cats_and_Shit. •. I think you could say that the assignment operator is parametrically polymorphic, while memcpy uses subtyping. Parametric polymorphism is when an operation is defined abstractly such that works on any type (or any type with certain qualities); for assignment in C that is everything except arrays.

  9. structure assignment vs memcpy

    Structure assignments have been supported since C90. Of course if you only want to assign some members of a struct object to another, then you'll have to do it manually. Using memcpy is not usually necessary, since the language directly supports copying structures. Mar 10 '07 # 2. Richard Tobin.

  10. memcpy() in C/C++

    The memcpy() function in C and C++ is used to copy a block of memory from one location to another. Unlike other copy functions, the memcpy function copies the specified number of bytes from one memory location to the other memory location regardless of the type of data stored.. It is declared in <string.h> header file. In C++, it is also defined inside <cstring> header file.

  11. Difference in assigning a char variable with memcpy() or directly

    To know the difference we must start by clarifying concepts. In C++ everything has a type, including text literals. Thus, the literal "juan"has a type that is a constant 1 const char[5] formation of five characters. It's five characters times the four letters plus the string termination character and it's constant because it's a literal.

  12. memcpy C Function

    What is memcpy() memcpy() is a standard function used in the C programming language to copy blocks of memory from one place to another. Its prototype is defined in the string.h header file as follows:. void *memcpy(void *dest, const void *src, size_t n); The memcpy() function copies the contents of a source buffer to a destination buffer, starting from the memory location pointed to by src ...

  13. memccpy

    Return value. If the byte (unsigned char) c was found, memccpy returns a pointer to the next byte in dest after (unsigned char) c.Otherwise it returns a null pointer. [] NoteThe function is identical to the POSIX memccpy.. memccpy (dest, src, 0, count) behaves similar to strncpy (dest, src, count), except that the former returns a pointer to the end of the buffer written, and does not zero-pad ...

  14. Memcpy vs assignment in C

    Memcpy vs assignment in C. c memcpy struct variable-assignment. ... 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 ...

  15. memcpy vs assignment in C -- should be memmove?

    o->i = *i; struct outer o; // assign a bunch of fields in o->i... frob(&o.i, o); return 0; If gcc decides to replace that assignment with memcpy, then it's an invalid call because the source and dest overlap. Obviously, if I change the assignment statement in frob to call memmove instead, then the problem goes away.

  16. Should memcpy and the assignment operator (=) be ...

    Should memcpy and the assignment operator (=) be interchangeable when reading/writing bytes to a void* or char* on the heap in c/c++? I hope this question isn't to specific or inappropriately placed but I'm not sure where to ask and haven't been able to find any answers via Google. Also, sorry in advance but I can't share my code due to my ...

  17. Assignment vs Memcpy

    return 0; when i use the default assignment operator of the Test struct, the execution time is around 6600 milliseconds, but when i overload the assignment operator use memcpy with the size of the block to copy being known at compile time, the same program executes at around 3800 milliseconds.

  18. In what cases should I use memcpy over standard operators in C++?

    Don't go for premature micro-optimisations such as using memcpy like this. Using assignment is clearer and less error-prone and any decent compiler will generate suitably efficient code. If, and only if, you have profiled the code and found the assignments to be a significant bottleneck then you can consider some kind of micro-optimisation, but ...

  19. std::memcpy

    Return value. dest [] Notestd::memcpy may be used to implicitly create objects in the destination buffer.. std::memcpy is meant to be the fastest library routine for memory-to-memory copy. It is usually more efficient than std::strcpy, which must scan the data it copies or std::memmove, which must take precautions to handle overlapping inputs.. Several C++ compilers transform suitable memory ...

  20. memcpy, wmemcpy

    memcpy copies count bytes from src to dest; wmemcpy copies count wide characters. If the source and destination regions overlap, the behavior of memcpy is undefined. Use memmove to handle overlapping regions. Important. Make sure that the destination buffer is large enough to accommodate the number of copied characters.

  21. c++

    8. When the data is copied into char[] buffer, it may not be properly aligned in memory for access as multi-byte types. Copying the data back into struct restores proper alignment. If I want to deserialize the individual values eg: uint16_t len = 0; memcpy(&len, buf, sizeof(len)); Assuming that you have copied the struct into buf, this is ...