290 Intermediate C Programming
DecP ack_de stroy ( dp );29
return EXIT _SUCCES S ;30
}31
Here is the Makefile:
GCC = gcc1
CFLAGS = -g - Wall - Wshadow2
VALGRIND = valgrind -- tool = memc h eck -- verbose --log - file3
4
decpack : d e cp ack . c decpack . h main .c5
$( GCC ) $ ( CFLAGS ) decpack .c main .c -o $@6
$( VALGRIND )= valgr indlog ./ decpack7
8
clean :9
/ bin / rm -f *. o decpack * log10
17.3 Binary File and Pointer
Section 16.6 describes how to use fread and fwrite to read and write the attributes of
an object. What happens if the object contains one or more pointers? Consider the following
example:
// str uctfile .c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
#in clude < time .h >4
#pragma pack (1) // tell compiler not to pad any space5
typedef s t ru ct6
{7
int length ;8
int * data ;9
} Array ;10
// for simplicity , this progr a m does not check errors11
int main ( i n t argc , char ** argv )12
{13
int length = 10;14
char * f i lename = " data ";15
// create an object16
Array * aptr1 = NULL ;17
printf (" sizeof ( aptr1 ) = % dn " , ( i nt ) s i z e o f ( aptr1 ) );18
aptr1 = malloc ( s i z e o f ( Array ) );19
printf (" sizeof ( aptr1 ) = %d , sizeof ( Array ) = %d n" ,20
( i n t ) s i z e o f ( aptr1 ) , ( i n t ) s i z e o f ( Array )) ;21
// allocat e memory for the data22
aptr1 -> length = length ;23
aptr1 -> data = malloc ( s i z e o f ( i n t ) * ( aptr1 -> length )) ;24
printf (" sizeof ( aptr1 ): %d , sizeof ( aptr1 -> data ): %d n" ,25
( i n t ) s i z e o f ( aptr1 ) , ( i n t ) s i z e o f ( aptr1 -> data )) ;26