Understanding memcpy Behavior with Array and Pointer

Have you ever wondered why the two memcpy lines in your code snippet work exactly the same? In this article, we'll dive into the behavior of memcpy when working with arrays and pointers in C.

Address of Array and First Element

When you pass an array as an argument to a function or use it in an expression, it automatically converts to a pointer to its first element. This conversion is what allows the memcpy function to work with both buff and &buff[0] .

Unary & Operator

The unary & operator is an exception to the array-to-pointer conversion rule. It gives the address of its operand instead of converting an array to a pointer. So, when you write &buff , you get a pointer to the whole array.

Same Starting Location

The starting location of the first element of an array and the starting location of the array itself are the same. Therefore, &buff and buff have the same value, but different types. But, in both cases, data is copied to the same location.

Additionally, it's worth noting that the type difference becomes irrelevant in the context of memcpy . The first parameter of memcpy is declared as void * restrict , which means both &buff and buff are converted to the same type before the call.

In summary, the two memcpy lines work the same because the array buff automatically converts to a pointer to its first element, and the unary & operator gives the address of the whole array. The starting location of the first element and the array itself are the same, causing the data to be copied to the same location.

Next time you encounter a similar scenario, you'll understand why the two versions of memcpy have identical behavior!

Understanding memcpy Behavior with Array and Pointer

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…

cppreference.com

Memcpy, memcpy_s.

(C11)
(C11)
Functions
Character manipulation
atolatoll (C99)
strtoll (C99)
strtoull (C99)
strtodstrtold (C99)
strtoumax (C99)
strnlen_s (C11)
strtok_s (C11)
(1)
* memcpy( void *dest, const void *src, count ); (until C99)
* memcpy( void *restrict dest, const void *restrict src, count ); (since C99)
void *restrict dest, rsize_t destsz,
                  const void *restrict src, rsize_t count );
(2) (since C11)
  • dest or src is a null pointer
  • destsz or count is greater than RSIZE_MAX
  • count is greater than destsz (buffer overflow would occur)
  • the source and the destination objects overlap
Parameters Return value Notes Example References See also

[ edit ] Parameters

dest - pointer to the object to copy to
destsz - max number of bytes to modify in the destination (typically the size of the destination object)
src - pointer to the object to copy from
count - number of bytes to copy

[ edit ] Return value

[ edit ] notes.

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 memory-copying loops to memcpy calls.

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

[ edit ] Example

Possible output:

[ edit ] References

  • C11 standard (ISO/IEC 9899:2011):
  • 7.24.2.1 The memcpy function (p: 362)
  • K.3.7.1.1 The memcpy_s function (p: 614)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.21.2.1 The memcpy function (p: 325)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.11.2.1 The memcpy function

[ edit ] See also

memmove_s (C11) moves one buffer to another
(function)
wmemcpy_s (C11) copies a certain amount of wide characters between two non-overlapping arrays
(function)
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 30 April 2018, at 15:30.
  • This page has been accessed 186,453 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

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?

memcpy vs pointer assignment

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

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

> Linux >

memcpy(3) — Linux manual page

| | | | | | | | | |

NAME         top

Library         top, synopsis         top, description         top, return value         top, attributes         top, standards         top, history         top, caveats         top, see also         top, colophon         top.

Pages that refer to this page: bcopy(3) ,  bstring(3) ,  cmsg(3) ,  CPU_SET(3) ,  memccpy(3) ,  memmove(3) ,  mempcpy(3) ,  size_t(3type) ,  void(3type) ,  wmemcpy(3) ,  feature_test_macros(7) ,  signal-safety(7) ,  string_copying(7)

HTML rendering created 2024-06-26 by , author of .

For details of in-depth that I teach, look .

Hosting by .

cppreference.com

Search

std:: memcpy

(C++11)
(C++11)
(C++11)
Null-terminated strings
Classes
Functions
Character manipulation
(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 .

If the objects overlap, the behavior is undefined. If the objects are not trivially copyable (e.g. scalars, arrays, C-compatible structs), the behavior is undefined.

Parameters Return value 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 ] example, [ edit ] see also.

moves one buffer to another
(function)
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
  • In other languages
  • This page was last modified on 15 June 2012, at 15:06.
  • This page has been accessed 9,767 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Runtime Protection
  • Continuous Monitoring
  • Threat Detection
  • Sternum Labs
  • Fundamentals
  • Regulation Learning Center
  • Video Series
  • Case Studies

SUGGESTED READ

IoT Security:

Learn about cyber threat protections for devices and networks.

Medical Device Regulations:

Unpack the strict regulations medical device manufacturers face.

Understand the challenges and security concerns around real-time operating systems (RTOS).

Learn more about Sternum

Get the latest

Join our team

  • Free Evaluation Kit

Experience all platform features

  • Book a demo

memcpy C Function – Syntax, Examples, and Security Best Practices

Igal Zeifman

Igal Zeifman

6  min read | min read | 23/04/2023

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:

The memcpy() function copies the contents of a source buffer to a destination buffer, starting from the memory location pointed to by src , and continuing for n bytes. The areas of memory should not overlap, and the behavior is undefined if they do.

The function is commonly used in C programming for tasks such as copying the contents of one array to another, or for copying structures or other data types that are not handled by simple assignment. Using memcpy() is often preferred over a loop-based approach to copying memory, as it is generally faster and more efficient.

Common Use Cases for the memcpy() Function

The versatility of the memcpy() function makes it a go-to option for a variety of programming tasks involving strings, arrays, and pointers in the C programming language, for instance:

  • Strings: memcpy() is often used for tasks such as concatenation or copying substrings. For example, you could use memcpy to copy a portion of a source string to a dest buffer or to concatenate two strings together into a new buffer.
  • Arrays: memcpy() can be used to copy the contents of one array to another. This is often useful when working with large arrays that may be time-consuming to copy using a loop-based approach. memcpy can also be used to manipulate arrays by copying subsets of elements from one location to another.
  • Pointers: The memcpy() function enables the copying of the contents of one memory location to different places, even when the source and destination are not contiguous blocks of memory. This is useful when working with complex data structures or when copying data between non-contiguous memory spaces.

How memcpy() Works: Syntax and Code Example

The memcpy() function takes three arguments:

  • dest : a pointer to the destination buffer location where the data is to be copied.
  • src : a pointer to the source buffer from where the data is to be copied.
  • n : the number of copied bytes.

Here is a simple example of how it all comes together. The below code copies the content of src (the source buffer) to dest (the destination buffer). Note that this code uses the sizeof operator instead of n (the number of bytes to be copied), which allows the program to copy all of the bytes from the source buffer.

memcpy-output-example

memcpy Alternatives

Of course, memcpy() is not the only way to move memory blocks around in C. Here is a quick rundown of some alternatives:

memcpy vs. memmove

memcpy() and memmove() are both standard C-language library functions used to copy blocks of memory between different locations. The main difference between memcpy() and memmove() is in how they handle overlapping memory regions. When copying memory, memcpy assumes that the source and destination memory regions do not overlap, and will produce undefined behavior if they do. In contrast, memmove() is designed to handle overlapping memory regions and will copy the memory correctly regardless of whether the regions overlap or not.

In the example below the memcpy() function enables the copying of the substring “world!” from the str array to the buffer array. However, since the source and destination regions overlap, the function’s behavior is not defined, and the program may produce unexpected results.

The memmove() function does exactly the same, copying the substring to the buffer array, but it will be correctly handle the overlapping regions.

memcpy vs. strcpy

strcpy() is another standard C-language library function and (you guessed it) it’s also used to copy memory between locations. The main difference between it and memcpy() is the type of data they are designed to handle. Specifically, memcpy() is a low-level function that can copy any type of data, including non-character data types such as integers, floating-point numbers, and structures. In contrast, strcpy() is specifically designed to copy null-terminated character strings, and will produce undefined behavior if used with non-string data.

Another important difference between memcpy() and strcpy() is the way they handle the null terminator character. memcpy() does not add a null terminator to the copied data, so it is up to the programmer to ensure that the destination buffer is properly terminated. In contrast, strcpy() automatically adds a null terminator to the copied string, so the programmer does not need to explicitly add one.

The simple example below illustrates the difference between the two functions. In this example, memcpy is used to copy the contents of the source array to the buffer array. Since it does not add a null terminator, the programmer must manually add one to ensure that the copied string is properly terminated.

In contrast, the strcpy function is used to copy the same string to the buffer array, and automatically adds a null terminator to the end of the copied string.

Security Best Practices

memcpy() can be used securely if it is used with care. However, since it is a low-level function that allows direct memory access, it can be dangerous if used incorrectly.

There are two primary security concerns with memcpy() :

  • Buffer overflow vulnerabilities : If the destination buffer is too small to hold the copied data, the function can overwrite adjacent memory regions and cause undefined behavior, which could potentially be exploited by an attacker. To avoid this, it is essential to ensure that the dest buffer is sufficiently large to hold the copied data and to check that the size of the copied data does not exceed the size of the buffer.
  • Memory leaks:  If the function is used to copy sensitive information, such as passwords or cryptographic keys, and the memory is not properly cleared after use, an attacker may be able to access this information by reading the memory.

To avoid these security concerns, it is important to follow these best practices when using memcpy() :

  • Ensuring that the destination buffer has an adequate size to hold the copied data.
  • Checking the amount of data being copied to ensure it does not exceed the capacity of the buffer.
  • Avoiding the use of strcpy with non-string data types, since it can result in undefined behavior and potential security vulnerabilities.
  • Clearing the memory after use, especially if the data being copied is sensitive.
  • Using standard library functions like strncpy and memset that are designed to handle strings and memory operations safely, rather than manually writing code that accesses memory directly.

Deterministic Security for IoT with Sternum

The memcpy() function is a commonplace culprit behind many vulnerabilities in IoT/embedded devices.

Sternum’s patented EIV™ ( embedded integrity verification ) technology protects from these with runtime (RASP-like) protection that deterministically prevents all memory and code manipulation attempts, offering blanket protection from a broad range of software weaknesses (CWEs), including the ones related to improper use of memcpy() and other exploitable functions.

Embedding itself directly in the firmware code, EIV™ is agentless and connection agnostic. Operating at the bytecode level, it is also universally compatible with any IoT device or operating system ( RTOS , Linux, OpenWrt , Zephyr , Micirum, FreeRTOS, etc.) and has a low overhead of only 1-3%, even on legacy devices.

The runtime protection features are also augmented by (XDR-like) threat detection capabilities of Sternum’s Cloud platform, its AI-powered anomaly detection, and extended monitoring capabilities.

To learn more, check out these case studies of how this technology was used to:

– Help a Fortune 500 company catch memory leaks in pre-production (Zephyr device)

– Uncover buffer overflow vulnerabilities in 80,000 NAS devices

– Uncover buffer overflow vulnerability in a very popular smart plug device

Also check out the video below to see Sternum EIV™ in action, as it provides out-of-the-box mitigation of Ripple20 malware, used for memory corruption attacks.

JUMP TO SECTION

Take Sternum for a Test Drive with a Free Evaluation Kit

Take Sternum for a Test Drive with a Free Evaluation Kit

Enter data to download case study.

By submitting this form, you agree to our Privacy Policy.

Related articles

Top Linux Security Vulnerabilities and How to Prevent Them

Top Linux Security Vulnerabilities and How to Prevent Them

Lian Granot

Lian Granot

7  min read | 26/08/2024

Linux Security Pros and Cons and 7 Ways to Secure Linux Systems

Linux Security Pros and Cons and 7 Ways to Secure Linux Systems

11  min read | 12/08/2024

Getting Started with IoT Device Observability: What Should You Trace?

Getting Started with IoT Device Observability: What Should You Trace?

5  min read | 02/08/2024

Looking to learn more? Book a demo with our experts ►►

Lorem ipsum dolor sit amet.

  • IoT Security
  • Medical Device Regulation
  • Vulnerability Management
  • Keynote: The Hacker Perspective
  • Webinar: Medtronic Monitoring & Debugging

© Sternum 2024 · All rights reserved

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

Struct assignment or memcpy? [duplicate]

If I want to replicate a structure in another one (in C), what are the pro&con's of :

Are they equivalent ? Is there a difference in performance or memory use ?

  • variable-assignment

hmijail's user avatar

  • 4 Just be careful of memory allocation inside the struct. For example if you have a struct that contains a pointer to a string and you allocate memory for the string. That memory does not get copied. the pointer to the memory gets copied, but not the memory itself. In other word this type of assignment is not a deep copy. Neither is vanilla memcpy for that mater. It can get confusing as to who owns the allocated memory. –  Pemdas Commented Mar 21, 2011 at 15:22
  • I think this question is more suited to Stackoverflow. –  karlphillip Commented Mar 21, 2011 at 16:52
  • 2 I think this question was already well answered here: stackoverflow.com/q/4931123/176769 –  karlphillip Commented Mar 21, 2011 at 16:54

4 Answers 4

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.

Alexander Gessler's user avatar

  • 3 Major problem on s = mystruct between struct s and struct * s. Both work nicely with equals, so you can't see the difference by reading. *s gives you identical, while struct s gives you a copy. When it comes time to deallocate(s), this works fine with the identical struct * s; but it leaks mystruct if you foolishly do only one dealloc with the struct s version. It is also faster to work with pointers. Just keep what you're doing in mind, and then things should be fine. YMMV. –  DragonLord Commented Mar 7, 2015 at 2:55

I'm not sure of the performance difference, although I would guess most compilers would use memcpy under the hood.

I would prefer the assignment in most cases, it is much easier to read and is much more explicit as to what the purpose is. Imagine you changed the type of either of the structs, the compiler would guide you to what changes were needed, either giving a compiler error or by using an operator= (if one exists). Whereas the second one would blindly do the copy with the possibility of causing a subtle bug.

Andy Lowry's user avatar

Check out this conversation about the very same topic: http://bytes.com/topic/c/answers/670947-struct-assignment

Basically, there are a lot of disagreements about the corner cases in that thread on what the struct copy would do. It's pretty clear if all the members of a struct are simple values (int, double, etc.). The confusion comes in with what happens with arrays and pointers, and padding bytes.

Everything should be pretty clear as to what happens with the memcpy , as that is a verbatim copy of every byte. This includes both absolute memory pointers, relative offsets, etc.

Berin Loritsch's user avatar

There is no inherent reason why one would be better in performance than the other. Different compilers, and versions of them, may differ, so if you really care, you profile and benchmark and use facts as a basis to decide.

A straight assignment is clearer to read.

Assignment is a teeny bit riskier to get wrong, so that you assign pointers to structs rather than the structs pointed to. If you fear this, you'll make sure your unit tests cover this. I would not care about this risk. (Similarly, memcpy is risky because you might get the struct size wrong.)

  • There's nothing risky about memcpy if you use sizeof and the correct struct. I suppose you could get the struct wrong and there would be no error. I think you'd probably get a segmentation fault eventually though. –  Michael K Commented Mar 21, 2011 at 17:05

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

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • How to avoid repeated input while using newcommand?
  • Some of them "have no hair"
  • How to assign a definition locally?
  • Why the simulator should be a PPT in simulation-based security?
  • Xcode 16.0 : unexpected service error: The Xcode build system has crashed
  • How would you say "must" as in "Pet rabbits must be constantly looking for a way to escape."?
  • What can I do to limit damage to a ceiling below bathroom after faucet leak?
  • Apple IIgs to VGA adapter
  • Terminated employee will not help the company locate its truck
  • How to add Z-axis to analog oscilloscope?
  • Can a 20A circuit mix 15A and 20A receptacles, when a 20A is intended for occassional space heater use?
  • Why believe in the existence of large cardinals rather than just their consistency?
  • Wondering about ancient methods of estimating the relative planetary distances
  • How can "chemical-free" surface cleaners work?
  • Does Tempestuous Magic allow you to avoid attacks of opportunity *after* they have already triggered?
  • Change of variable, u = y(x)
  • What is a “bearded” oyster?
  • Fundamental Sampling Theorem
  • Cheapest / Most efficient way for a human Wizard to not age?
  • "First et al.", many authors with same surname, and IEEE citations
  • Why Doesn't the cooling system on a rocket engine burn the fuel?
  • Why are no metals green or blue?
  • string quartet + chamber orchestra + symphonic orchestra. Why?
  • Why a relay frequently clicks when a battery is low?

memcpy vs pointer assignment

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Write your own memcpy() and memmove()

The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype.

The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of this idea. 

Time Complexity: O(n)

Auxiliary Space: O(1)

What is memmove() ?

memmove() is similar to memcpy() as it also copies data from a source to destination. memcpy() leads to problems when source and destination addresses overlap as memcpy() simply copies data one by one from one location to another. For example consider below program. 

Since the input addresses are overlapping, the above program overwrites the original string and causes data loss. 

How to implement memmove()?

The trick here is to use a temp array instead of directly copying from src to dest. The use of temp array is important to handle cases when source and destination addresses are overlapping. 

Optimizations: The algorithm is inefficient (and honestly double the time if you use a temporary array). Double copies should be avoided unless if it is really impossible. In this case though it is easily possible to avoid double copies by picking a direction of copy. In fact this is what the memmove() library function does. By comparing the src and the dst addresses you should be able to find if they overlap. – If they do not overlap, you can copy in any direction – If they do overlap, find which end of dest overlaps with the source and choose the direction of copy accordingly. – If the beginning of dest overlaps, copy from end to beginning – If the end of dest overlaps, copy from beginning to end – Another optimization would be to copy by word size. Just be careful to handle the boundary conditions. – A further optimization would be to use vector instructions for the copy since they’re contiguous.

Please Login to comment...

Similar reads.

  • CPP-Library
  • cpp-pointer
  • Best External Hard Drives for Mac in 2024: Top Picks for MacBook Pro, MacBook Air & More
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. C++: How to use memcpy with pointer **?

    memcpy vs pointer assignment

  2. C++ : Why are memcpy() and memmove() faster than pointer increments

    memcpy vs pointer assignment

  3. Array : memcpy vs for loop

    memcpy vs pointer assignment

  4. Memcpy vs Memmove: Crucial Differences

    memcpy vs pointer assignment

  5. memcpy C Function

    memcpy vs pointer assignment

  6. memcpy() function

    memcpy vs pointer assignment

VIDEO

  1. Array of pointers vs pointer to an array #mysirg

  2. pointerAssignment

  3. C 12: Incrementing a pointer

  4. light😬 vs pointer💥🗿

  5. Learn to Code C++ Pointers: Pointer Assignment PartI

  6. C Language || Pointers in C || Part-4: Pointer Assignment in C || Telugu Scit Tutorial

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. Is memcpy of a pointer the same as assignment?

    Overwriting the contents of a pointer variable is no different than overwriting the contents of normal int variable. So yes, doing e.g. memcpy (&p, &pa1, sizeof p) is equivalent of the assignment p = pa1, but might be less efficient. Lets try it a bit differently instead:

  3. c

    After the memcpy(), on the other hand, if the behavior is defined at all (see above) then each pointer points to a separate copy of the same data. Freeing one of them frees only that copy -- in that case it is still ok to dereference the other one.

  4. Understanding memcpy Behavior with Array and Pointer

    The first parameter of memcpy is declared as void * restrict, which means both &buff and buff are converted to the same type before the call. Conclusion. In summary, the two memcpy lines work the same because the array buff automatically converts to a pointer to its first element, and the unary & operator gives the address of the whole array ...

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

  6. memcpy, memcpy_s

    memcpy, memcpy_s. 1) Copies count characters from the object pointed to by src to the object pointed to by dest. Both objects are interpreted as arrays of unsigned char. The behavior is undefined if access occurs beyond the end of the dest array. If the objects overlap (which is a violation of the restrict contract) (since C99), the behavior is ...

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

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

    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: persona f1() { persona p; p.nombre = "juan"; return p; }

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

  10. memcpy(3)

    The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove(3) if the memory areas do overlap. RETURN VALUE top The memcpy() function returns a pointer to dest. ATTRIBUTES top For an explanation of the terms used in this section, see attributes(7)

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

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

  13. std::memcpy

    std:: memcpy. std:: memcpy. Copies count bytes from the object pointed to by src to the object pointed to by dest. If the objects overlap, the behavior is undefined. If the objects are not trivially copyable (e.g. scalars, arrays, C-compatible structs), the behavior is undefined.

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

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

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

  17. memcpy, memcpy_s

    Notes. 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 memory-copying loops to memcpy calls.

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

  19. c

    A straight assignment is clearer to read. Assignment is a teeny bit riskier to get wrong, so that you assign pointers to structs rather than the structs pointed to. If you fear this, you'll make sure your unit tests cover this. I would not care about this risk. (Similarly, memcpy is risky because you might get the struct size wrong.)

  20. Write your own memcpy() and memmove()

    The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype. ... If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class.