Created
October 27, 2017 22:17
-
-
Save gpakosz/e21fd2262e056a9645c4a1e20e05e972 to your computer and use it in GitHub Desktop.
memcmp() and sizeof()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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