memory allocation in c
DESCRIPTION
Memory allocation in c S-TeacherTRANSCRIPT
Dynamic Memory Allocation
The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this functions, which can be used to allocate and free memory during the program execution.
Dynamic Memory Allocation Functions
malloc()A block mf memory may be allocated using the
function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:
ptr=(cast-type*)malloc(byte-size);
ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size
malloc() ExampleExample: x=(int*)malloc(100*sizeof(int));
On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.
Calloc
Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:
ptr=(cast-type*) calloc(n,elem-size);
Calloc(Contd.)
calloc() allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
free()
Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required.
free(ptr); ptr is a pointer that has been created by using malloc or calloc
realloc The memory allocated by using calloc or
malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :
ptr=realloc(ptr,newsize);
FILE HANDLING
IntroductionFiles are places where data can be stored
permanently.Some programs expect the same set of data
to be fed as input every time it is run.Cumbersome.Better if the data are kept in a file, and the
program reads from the file.Programs generating large volumes of
output.Difficult to view on the screen.Better to store them in a file for later viewing/
processing
Basic File OperationsOpening a fileReading data from a fileWriting data to a fileClosing a file
Opening a FileA file must be “opened” before it can be used.
FILE *fp;
: fp = fopen (filename, mode);fp is declared as a pointer to the data type FILE.filename is a string - specifies the name of the
file.fopen returns a pointer to the file which is used
in all subsequent file operations. mode is a string which specifies the purpose of
opening the file:“r” :: open the file for reading only“w” :: open the file for writing only“a” :: open the file for appending data to it
Closing a FileAfter all operations on a file have been
completed, it must be closed.Ensures that all file data stored in memory
buffers are properly written to the file.
General format: fclose (file_pointer) ; FILE *xyz ; xyz = fopen (“test”, “w”) ; ……. fclose (xyz) ;
Read/Write Operations on Files
The simplest file input-output (I/O) function are getc and putc.
getc is used to read a character from a file and return it.
char ch; FILE *fp;…..ch = getc (fp) ;
getc will return an end-of-file marker EOF, when the end of the file has been reached.
putc is used to write a character to a file.char ch; FILE *fp;……putc (c, fp) ;
main() { FILE *in, *out ; char c ;
in = fopen (“infile.dat”, “r”) ; out = fopen (“outfile.dat”, “w”) ; while ((c = getc (in)) != EOF) putc (toupper (c), out); fclose (in) ; fclose (out) ;}
Basic operations of files(Contd.)We can also use the file versions of scanf and
printf, called fscanf and fprintf.General format:
fscanf (file_pointer, control_string, list) ; fprintf (file_pointer, control_string, list) ;
Examples:fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ;fprintf (out, “\nThe result is: %d”, xyz) ;
Command line argument
Command line arguments are parameters supplied to a program, when the program is invoked.
How do these parameters get into the program?Every C program has a main function.main can take two arguments conventionally called
argc and argv. Information regarding command line arguments are
passed to the program through argc and argv.
INTRODUCTION TO C PREPROCESSOR
C Preprocessor
OverviewPreprocessor DirectivesConditional Compilation
Overview
Six phases to execute C:1. Edit2. Preprocess3. Compile4. Link5. Load6. Execute
C Preprocessor
All preprocessor directives begin with #Possible actions
Inclusion of other filesDefinition of symbolic constants & macrosConditional compilation of program codeConditional compilation of preprocessor
directives
Preprocessor Directives
#define for symbolic constants#define identifier text
Creates symbolic constants The “identifier” is replaced by “text” in the
programExample
#define PI 3.14
area = PI * radius * radius; Replaced by “area = 3.14 * radius * radius” by
preprocessor before compilation
Conditional Compilation Controls the execution of preprocessor
directives & compilation of codeDefine NULL, if it hasn’t been defined yet#if !defined(NULL)#define NULL 0
#endifUse to comment out code (for comments)#if 0code prevented from compiling
#endif
THANK YOU