Skip to content

Instantly share code, notes, and snippets.

@gpakosz
Created October 27, 2017 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpakosz/e21fd2262e056a9645c4a1e20e05e972 to your computer and use it in GitHub Desktop.
Save gpakosz/e21fd2262e056a9645c4a1e20e05e972 to your computer and use it in GitHub Desktop.
memcmp() and sizeof()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdbool.h>
struct Foo
{
int i;
char j;
};
void trash(size_t size)
{
int fd = open("/dev/random", O_RDONLY);
char* buffer = (char*)malloc(size);
read(fd, buffer, size);
free(buffer);
close(fd);
}
int main(int argc, char* argv[])
{
printf("sizeof(struct Foo): %d\n", (int)sizeof(struct Foo));
bool fail = false;
for (;!fail;)
{
trash(10000);
struct Foo* foo1 = (struct Foo*)malloc(sizeof(struct Foo));
trash(10000);
struct Foo* foo2 = (struct Foo*)malloc(sizeof(struct Foo));
foo1->i = foo2->i = 1;
foo1->j = foo2->j = 2;
if (memcmp(foo1, foo2, sizeof(struct Foo)) == 0)
{
printf(".");
}
else
{
printf("X\n");
fail = true;
}
free(foo1);
free(foo2);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment