I have the following C program which requests some memory (str1), reads the content of a file into that space then frees it. Next, a block of the same size (str2) is requested, and the content is printed to stdout.
What I want is for str2 to contain the content of str1 so that the output is always the content of the file.
I am aware that what I am doing is undefined behaviour, in that I can't guarantee what the content of memory that has been allocated will contain. However, I'm trying to do some underhanded stuff for a demonstration where data from a file can be exfiltrated without it being obvious in a code review.
Almost all the time, I receive a block of memory at the same address for both str1 and str2, and most of the time when I run the program on macOS and Windows, the content of the file is printed. It seems to never happen on Linux (on Linux, calling free() seems to zero out the memory block).
Is there a way of making this more reliable on Windows and macOS, and is there any explanation for why it doesn't work at all on Linux?
My code is:
#include <stdlib.h>
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
char *str1 = malloc(4096*sizeof(char));
fread(str1, 1, 4096, f);
free(str1);
char *str2 = malloc(4096);
printf("Content: %s\n", str2);
free(str2);
}