Discussion: Misallocation
Understand how pointer variables affect memory allocation in C, particularly when using the sizeof operator. This lesson helps you identify common misallocation errors caused by using sizeof on pointers rather than on the structure type itself. Learn to correctly allocate and write data to files by referencing structure sizes instead of pointer sizes to avoid incomplete data writes and errors in your C programs.
We'll cover the following...
We'll cover the following...
Run the code
Now, it's time to execute the code and observe the output.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
struct raw { int value; char string[32]; };
FILE *outfile;
struct raw *data;
/* allocate and fill the structure */
data = malloc( sizeof(struct raw) );
data->value = 60;
strcpy( data->string, "This is a string\n" );
/* open a file and save the data */
outfile = fopen("data.dat","w");
if( outfile==NULL )
exit(1);
fwrite(data, sizeof(data), 1, outfile);
fclose(outfile);
puts("File written");
/* clean up */
free(data);
return(0);
}C code for the given puzzle
Understanding the output
As we know now, the first line of the output is File written.
It’s true, the file was written. The question is, what was written? The hexdump program can confirm what was written. Here is that program’s output:
$ hexdump data.dat0000000 003c 0000 6854 73690000008
Code output
Does it look like ...