
memcpy
Q: Why is memcpy safer than pointer casting for type punning? 💡 Concept in a Nutshell memcpy is the "Official Copy Machine" of C: It doesn't care if your data is a math book or a cookbook; it only sees "paper" (Bytes) and duplicates them from point A to point B without violating language laws. 1. Life Analogy (The Librarian vs. The Xerox) Imagine you have a Math Book but you want to read it as a Cookbook . Pointer Casting ( *(int*)&f ) : This is like forcing a Librarian to read a Math book as a Cookbook. The Librarian will get confused because it violates the "Library Classification Rules" ( Strict Aliasing ). memcpy : This is like putting the Math book into a Xerox machine . The machine doesn't read the words; it just copies the ink onto new paper. Now you have "Cookbook-shaped" paper with "Math-ink" on it. It’s perfectly legal because the Xerox machine is allowed to touch any paper! 2. Code Example #include <stdio.h> #include <string.h> int main () { float f = 3 . 14 f ; int i ; // "
Continue reading on Dev.to
Opens in a new tab
