Académique Documents
Professionnel Documents
Culture Documents
Exercise
Write a program that compares two files and returns 0 if they are equal and I if they are not.
test2.c
This is a test line
Contd.
flag
1: Files not same 0: Files are same
Example
welcome to BITS
Example
Exercise
Rewrite the program which compares files (in slide 2), to accept the source and destination filenames from the command line. Include a check on the number of arguments passed.
Contd
Free Memory
Global Variables C Program instructions
malloc
calloc
free
realloc
malloc()
malloc reserves the memory during the program execution. malloc reserves a block of memory of specified size Returns void pointer: we can assign it to any type of pointer Syntax:
ptr = (cast-type *) malloc (byte-size);
Examples
1) 2) 3) 4) x = (int *) malloc (100*sizeof(int)); cptr = (char *) malloc (10); ptr = (int *) malloc (j * sizeof(int)); St_var = (struct store *) malloc (sizeof( struct store));
Note:
malloc allocates a block of contiguous bytes if heap is not sufficient to satisfy the request, malloc returns a NULL.
malloc example
Write a program to store values in an array and print the same.
malloc() example
calloc()
calloc() reserves the memory at program execution Syntax:
calloc() allocates multiple blocks of storage space, each of same size, and sets all bytes to zero. (malloc allocates a single block of space)
calloc() example
free()
Dynamically release the memory when not in use Syntax:
free(ptr);
ptr is a pointer to a memory block which has already been created by malloc or calloc To note: 1. Use of invalid pointer in the call can cause the system to crash. 2. It is not the pointer that is being released but rather what it points to 3. To release an array of memory that was allocated by calloc we need only to release the pointer once. It is an error to attempt to release elements individually
Reallocate
Syntax: ptr = realloc (ptr, newsize) Note: newsize may be larger or smaller than earlier size returns NULL if unsuccessful
realloc()
NOTICE
There will be a LAB Session for Thursday batch students on 2/9/2010 at 10.30 a.m.