I'm working on a project which must be coded in standard C. (Not C++.) A while ago, I wrote the below program, writes the contents of different structs into a binary file:
#include <stdio.h>
#include <stdlib.h>
typedef struct structA{
int a, b, c;
}AAA;
typedef struct structB{
int a, b, c, d, e;
}BBB;
int main( int argc, char **argv ){
// Create and open the output file
FILE *fd = fopen("test.txt", "w");
AAA* a1 = (AAA*)malloc( sizeof(AAA) );
AAA* a2 = (AAA*)malloc( sizeof(AAA) );
BBB* b1 = (BBB*)malloc( sizeof(BBB) );
a1->a = 1; a1->b = 2; a1->c = 3;
a2->a = 4; a2->b = 5; a2->c = 6;
b1->a = 10; b1->b = 20; b1->c = 30; b1->d = 40; b1->e = 50;
// Write all these structs to the file:
fwrite((char*)&a1, sizeof(AAA), 1, fd);
fwrite((char*)&a2, sizeof(AAA), 1, fd);
fwrite((char*)&b1, sizeof(BBB), 1, fd);
// Close the file
fclose( fd );
free( a1 );
free( a2 );
free( b1 );
printf("END OF PROGRAM.\n");
return 0;
}
The above works perfectly… even though I can’t tell by looking at the output:
me@ubuntu:/home/me# more test.txt
▒$▒&V
me@ubuntu:/home/me#
I have another program which can read this file and extract all the information from the structs. So I know the above code gives me exactly what I want.
But now, I need to write those structs into a block of allocated memory, not into a file. I thought it would be easy:
#include <stdio.h>
#include <stdlib.h>
typedef struct structA{
int a, b, c;
}AAA;
typedef struct structB{
int a, b, c, d, e;
}BBB;
int main( int argc, char **argv ){
u_char* BlockOfMemory = (u_char*) malloc( sizeof(u_char) * 100 );
AAA* a1 = (AAA*)malloc( sizeof(AAA) );
AAA* a2 = (AAA*)malloc( sizeof(AAA) );
BBB* b1 = (BBB*)malloc( sizeof(BBB) );
a1->a = 1; a1->b = 2; a1->c = 3;
a2->a = 4; a2->b = 5; a2->c = 6;
b1->a = 10; b1->b = 20; b1->c = 30; b1->d = 40; b1->e = 50;
// Write all these structs into BlockOfMemory:
memcpy ( BlockOfMemory, &a1, sizeof( AAA ) );
memcpy ( (BlockOfMemory+sizeof(AAA)), &a2, sizeof( AAA ) );
memcpy ( (BlockOfMemory+sizeof(AAA)+sizeof(AAA)), &b1, sizeof( BBB ) );
printf("==> %hhn\n", BlockOfMemory);
free( a1 );
free( a2 );
free( b1 );
free( BlockOfMemory );
printf("END OF PROGRAM.\n");
return 0;
}
Did it work? I have no idea:
me@ubuntu:/home/me# gcc -Wall writeBlock.c
me@ubuntu:/home/me# ./a.out
==>
END OF PROGRAM.
me@ubuntu:/home/me#
The objective here is that the block of memory must contain the exact same information as the binary file did. I’m in the weird situation where my code compiles and runs, but given the tools I have (VI and GCC), I have no way to verify if my code is correct or way off the mark.
Can anyone advise? Also, would memcpy()
be the function to use here? Thank you.
EDIT: Fixed the first program when I mistakenly added a second "free( b1 );" because of a cut-n-paste error.