Skip to content

Instantly share code, notes, and snippets.

@hraban
Last active August 29, 2015 14:16
Show Gist options
  • Save hraban/d8f1faab48bd3b59feea to your computer and use it in GitHub Desktop.
Save hraban/d8f1faab48bd3b59feea to your computer and use it in GitHub Desktop.
Memcpy vs pointer dereference
/**
* Memcpy demonstration. Try compiling with:
*
* $ gcc -Wall -Werror -pedantic -std=c99 -S test.c -o test-deref.s
* $ gcc -Wall -Werror -pedantic -std=c99 -S test.c -DMEMCPY -o test-memcpy.s
* $ diff -u test-deref.s test-memcpy.s
*
* And play with -O0 to -O3 flags to see the effect of optimizations.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Char must point to at least sizeof(unsigned int) bytes of memory
*/
static unsigned int
test_cpy(const char *n) {
unsigned int res = 0;
#ifdef MEMCPY
memcpy(&res, n, sizeof(unsigned int));
#else
res = *((unsigned int *)n);
#endif
return res;
}
int
main(int argc, const char *argv[])
{
if (argc <= 1) {
printf("Requires at least one arg\n");
return 1;
}
if (strlen(argv[1]) < sizeof(unsigned int)) {
printf("Length of first arg must be at least %llu\n", (unsigned long long) sizeof(unsigned int));
return 1;
}
unsigned int res = test_cpy(argv[1]);
printf("Interpreting %s as unsigned int: %u\n", argv[1], res);
return 0;
}
@hraban
Copy link
Author

hraban commented Mar 8, 2015

Hi sebastian, you're right! #ifdef is cleaner. Good catch. GCC has me covered, because -D defines something as 1 by default, so this will still work. You can test it by putting a #error "Using memcpy" in the memcpy block. This will break only -DMEMCPY.

Thanks for the feedback, I'll change it to #ifdef as you suggested to prevent further confusion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment