r/C_Programming • u/musbur • Aug 07 '26
Does memcpy(buf, NULL, 0) create undefined behavior?
Question in the title. Am wondering if I need to take care of the special case.
23
Upvotes
r/C_Programming • u/musbur • Aug 07 '26
Question in the title. Am wondering if I need to take care of the special case.
37
u/gnolex Aug 07 '26
Yes, you invoke UB if either pointer is invalid or null.
18
u/WrStudio9017 Aug 07 '26
It depends on the version of the C standard. In current versions this is UB even though in many C libraries (glibc) this has always been a noop. I have heard that upcoming C standard versions will change so that this is not UB (but a noop instead).
Current versions of UBSAN and glibc flag this as UB due to the nonnull attribute on the first 2 arguments.
0 length memset (with null first arg) is in a similar situation.
Also I believe that Clang intentionally doesn't flag this as UB in terms of its optimization passes but gcc does.
16
u/WoodyTheWorker Aug 07 '26
Per standard, there's no guarantee.
Realistically, memcpy must not touch the buffers beyond the operation size, and if the size is 0, it's not allowed to touch the buffers at all.
The caveat seems originally introduced to accommodate segment-based protected memory architectures (i80286), where an invalid address exception can happen without even touching the memory.
2
u/SmokeMuch7356 Aug 07 '26
The behavior is undefined. N3220:
Passing a
NULLviolates this clause; since this clause is not a constraint, the behavior on such a violation is undefined, even though the last sentence says passing a size of 0 will not attempt to copy any characters.All "undefined behavior" means is that the compiler is not required to handle this situation in any particular way. It may act as a no-op (and probably will on any platform built after 1990), it may lead to a failure, it may do something else.
You'll need to add a check that both pointers are valid (or at least not
NULL). The zero size isn't a problem and will act as a no-op.1
u/musbur Aug 08 '26
Guys, thanks for the great discussion. I love it when Reddit sometimes feels like the Usenet in the 90s. Maybe memcpy()s signature could have given me the answer because even a zero-length array might have a valid memory address.
I don't really understand what
[restrict n]is supposed to mean, I only know restricted pointers.8
u/tstanisl Aug 07 '26
It is one of examples of "technical UB" which is UB according to the standard but it does not cause any practical problems except sanitizers configured to detect it directly.
The upcoming C2Y standard will allow it, c++ already does it so no sane compiler will experience problems. You may still get some annoying warnings from sanitizers, consider explicitly disabling them. For more details, take a look on the proposal 3322.
4
u/ReallyEvilRob Aug 07 '26
According to the man page for memcpy(3), neither of the pointer arguments are nullable, so if this doesn't cause a program crash it will certainly cause UB.
3
u/Dangerous_Region1682 Aug 07 '26
The reality is, in C, for portability amongst standards and to ensure you are doing what you think you are doing, a check on argument validity should probably be performed if you algorithm has any chance of calling memcpy() with null pointers or perhaps even zero size specification.
C library or system calls are rarely there to protect you from yourself. Handling the potential logic error of having null pointers is probably be something your program should be accounting for.
Most UB situations you can get yourself into can be prevented by checking for the validity of the parameters or situations you are trying to perform. C is a relatively low level language where the emphasis is on you to make sure you keep out of the reliance upon compilers and libraries to save you from yourself.
2
u/Chippors Aug 08 '26
Undefined behavior means the standard doesn't define it, but a compiler can still define it for a specific target system. You could absolutely do a memcpy from (const void*)0 on some systems, if you want to copy what's at that address - it could contain, for example, a block of system interrupt vectors mirrored from flash, that you want to copy to RAM, modify, and use as the vector table. Once you create hardware-dependent code you're operating outside the standard, but that's kind of obvious since it's both hardware and compiler specific at that point. Running it anywhere else or building it with a different toolchain will require work to port it.
3
u/flatfinger Aug 07 '26
The basic intention with the design of C was that if no special-case machine code would be needed to handle a particular corner case, whether because it would never arise or because any sensible way of handling general case on the target platform would naturally handle that corner case, neither the programmer nor the compiler should be required to produce special-case machine code.
If on some particular platform the most efficient way to handle
memcpy(dest,src,n)would be to compute either(char*)src+nor(char*)dest+n, and if on that same platform an attempt to displace a null pointer by zero bytes would do something weird rather than simply return a null pointer, an implementation for that platform would not be required to prevent such a weird outcome in thememcpy(0,ptr,0)ormemcpy(ptr,0,0)use cases. On the flip side, programmers writing code that accepts a (pointer,size) pair and is supposed to ignore the pointer when size is zero would only need to prevent passing such a pair tomemcpyin the size-zero case if their code might plausibly need to run on unusual platforms like the one described.Nowadays, however, the notion of "Undefined Behavior" has mutated from treating corner cases in a manner that would have been be defined on most but not all execution environments, to being an invitation for compilers to process nonsensically any corner cases where such corner cases might arrived. It is thus necessary to include unnecessary operations in source code, which are likely to end up being included in the generated machine code, to ensure that compilers won't treat the absence of such code as an invitation to "optimize out" other parts of the code that are actually necessary for correct operation.
1
u/SupportLast2269 Aug 07 '26
Yes. If one of the pointers is NULL its UB.
1
u/duane11583 Aug 08 '26
on most things this could be considered UB
ignoring the length (Zero) (ie if it was non zero) would segfault on modern linux systems
but because you are passing the length zero so i see nothing happening so no UB
on some bare metal platforms it would not segfault.
because for example on a cortex m3 that is often where the (flash) rom is located and the interrupt vector table default location is 0x00000000 so you would be copying the vector table entries. which is a valid memory space
0
u/sciencekm Aug 07 '26
This reminds me of old libraries that implement memcpy using conditional move instructions which would require a valid address. I don't think any modern library is bad enough to do this.
-1
u/lucidbadger Aug 07 '26
Compile with
-fsanitize=undefinedand it will tell you-2
u/Key_River7180 Aug 07 '26
Yes. You can assume It segfaults
-4
u/QuirkyXoo Aug 07 '26
First, I don’t understand at all this kind of questions. It’s like asking: “What happens if I go downhill without brakes?”
Second, according to the C standard, passing an invalid pointer to a function in the standard library always results in undefined behavior, which means the compiler is free to do whatever it wants. In practice, since the pointer is null and the size to be copied is zero, it can simply do nothing.