0% found this document useful (0 votes)
51 views

C - Dynamic Memory Allocation: Prev Next

The document discusses dynamic memory allocation in C. It describes the main functions used - malloc(), calloc(), realloc(), and free(). malloc() allocates memory without initializing it, calloc() allocates and initializes memory to zero, realloc() changes the size of previously allocated memory, and free() frees up memory. Examples are provided to illustrate how each function works. The differences between static and dynamic memory allocation as well as malloc() and calloc() are also summarized.

Uploaded by

sharadacg
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

C - Dynamic Memory Allocation: Prev Next

The document discusses dynamic memory allocation in C. It describes the main functions used - malloc(), calloc(), realloc(), and free(). malloc() allocates memory without initializing it, calloc() allocates and initializes memory to zero, realloc() changes the size of previously allocated memory, and free() frees up memory. Examples are provided to illustrate how each function works. The differences between static and dynamic memory allocation as well as malloc() and calloc() are also summarized.

Uploaded by

sharadacg
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

C Dynamic memory allocation

Prev Next
Dynamic memory allocation in C:
The process of allocating memory during program execution is called dynamic memory allocation.
Dynamic memory allocation functions in C:
C language offers 4 dynamic memory allocation functions. They are,
1. malloc()
. calloc()
!. realloc()
4. free()
S.no Function Syntax
1 malloc () malloc (num"er #si$eof(int))%
calloc () calloc (num"er, si$eof(int))%
! realloc () realloc (pointer&name, num"er # si$eof(int))%
4 free () free (pointer&name)%
1. malloc() function in C:
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initiali$e the memory allocated during execution. 't carries gar"age (alue.
malloc () function returns null pointer if it couldn)t a"le to allocate re*uested amount of memory.
+xample program for malloc() function in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 2 * si!eo"(char) );
i"( mem_allocation== #$%% )
{
&rint"('(ouldn)t able to allocate re*uested memory+n');
,
else
{
strc&y( mem_allocation-'"resh2re"resh.com');
,
&rint"('.ynamically allocated memory content / ' +
'0s+n'- mem_allocation );
"ree(mem_allocation);
,
,utput:
Dynamically allocated memory content : freshrefresh.com
. calloc() function in C:
calloc () function is also li-e malloc () function. .ut calloc () initiali$es the allocated memory to $ero.
.ut, malloc() doesn)t.
+xample program for calloc() function in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = calloc( 2- si!eo"(char) );
i"( mem_allocation== #$%% )
{
&rint"('(ouldn)t able to allocate re*uested memory+n');
,
else
{
strc&y( mem_allocation-'"resh2re"resh.com');
,
&rint"('.ynamically allocated memory content / ' +
'0s+n'- mem_allocation );
"ree(mem_allocation);
,
,utput:
Dynamically allocated memory content : freshrefresh.com
!. realloc() function in C:
realloc () function modifies the allocated memory si$e "y malloc () and calloc () functions to ne/
si$e.
'f enough space doesn)t exist in memory of current "loc- to extend, ne/ "loc- is allocated for the
full si$e of reallocation, then copies the existing data to ne/ "loc- and then frees the old "loc-.
4. free() function in C:
free () function frees the allocated memory "y malloc (), calloc (), realloc () functions and returns
the memory to the system.
+xample program for realloc() and free() functions in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 2 * si!eo"(char) );
i"( mem_allocation == #$%% )
{
&rint"('(ouldn)t able to allocate re*uested memory+n');
,
else
{
strc&y( mem_allocation-'"resh2re"resh.com');
,
&rint"('.ynamically allocated memory content / ' +
'0s+n'- mem_allocation );
mem_allocation=realloc(mem_allocation-1*si!eo"(char));
i"( mem_allocation == #$%% )
{
&rint"('(ouldn)t able to allocate re*uested memory+n');
,
else
{
strc&y( mem_allocation-'s&ace is e2tended u&to ' +
'1 characters');
,
&rint"('3esi!ed memory / 0s+n'- mem_allocation );
"ree(mem_allocation);
,
,utput:
Dynamically allocated memory content : freshrefresh.com
0esi$ed memory : space is extended upto 111 characters
Difference "et/een static memory allocation and dynamic memory allocation in C:
S.no Static memory allocation Dynamic memory allocation
1
'n static memory allocation, memory is allocated /hile
/riting the C program. 2ctually, user re*uested memory
/ill "e allocated at compile time.
'n dynamic memory allocation, memory is
allocated /hile executing the program. That
means at run time.

3emory si$e can)t "e modified /hile execution.


+xample: array
3emory si$e can "e modified /hile
execution.
+xample: 4in-ed list
Difference "et/een malloc() and calloc() functions in C:
S.no malloc() calloc()
1 't allocates only single "loc- of re*uested memory 't allocates multiple "loc-s of re*uested memory
int #ptr%ptr 5 malloc( 1 # si$eof(int) )%6or the
a"o(e, 1#4 "ytes of memory only allocated in one
"loc-.
int #ptr%7tr 5 calloc( 1, 1 # si$eof(int) )%6or the
a"o(e, 1 "loc-s of memory /ill "e created and
each contains 1#4 "ytes of memory.
Total 5 81 "ytes Total 5 1911 "ytes
!
malloc () doesn)t initiali$es the allocated memory.
't contains gar"age (alues
calloc () initiali$es the allocated memory to $ero
4
type cast must "e done since this function returns
(oid pointer int #ptr%ptr 5
(int#)malloc(si$eof(int)#1 )%
:ame as malloc () function int #ptr%ptr 5
(int#)calloc( 1, 1 # si$eof(int) )%
C :truct memory allocation
Prev Next
Do you -no/ ho/ memory is allocated for structure mem"ers in C;. <ou can learn "elo/ concepts of
C in this topic.
1. ho/ structure mem"ers are stored in memory;
. =hat is structure padding;
!. >o/ to a(oid structure padding;
1. >o/ structure mem"ers are stored in memory;
2l/ays, contiguous(ad?acent) memory locations are used to store structure mem"ers in memory.
Consider "elo/ example to understand ho/ memory is allocated for structures.
+xample program for memory allocation in C structure:
#include <stdio.h>
#include <string.h>
struct student
{
int id1;
int id2;
char a;
char b;
"loat &ercentage;
,;
int main()
{
int i;
struct student record1 = {1- 2- )4)- )5)- 6.7,;
&rint"('si!e o" structure in bytes / 0d+n'-
si!eo"(record1));
&rint"('+n4ddress o" id1 = 0u'- 8record1.id1 );
&rint"('+n4ddress o" id2 = 0u'- 8record1.id2 );
&rint"('+n4ddress o" a = 0u'- 8record1.a );
&rint"('+n4ddress o" b = 0u'- 8record1.b );
&rint"('+n4ddress o" &ercentage = 0u'-8record1.&ercentage);
return ;
,
,utput:
si$e of structure in "ytes : 19
2ddress of id1 5 9@A!@9@98
2ddress of id 5 9@A!@9@@
2ddress of a 5 9@A!@9@@9
2ddress of " 5 9@A!@9@@@
2ddress of percentage 5 9@A!@9@81
There are A mem"ers declared for structure in a"o(e program. 'n ! "it compiler, 4 "ytes of memory
is occupied "y int datatype. 1 "yte of memory is occupied "y char datatype and 4 "ytes of memory is
occupied "y float datatype.
7lease refer "elo/ ta"le to -no/ from /here to /here memory is allocated for each datatype in contiguous
(ad?acent) location in memory.
Datatype
Memory allocation in C (32 bit compiler)
From Address To Address Total bytes
int id1 675376768 675376771 4
int id2 675376772 675376775 4
char a 675376776 1
char b 675376777
Addresses 67537677! and 67537677" are le#t empty
(Do you know why? Please see Structure padding topic elow!
2
"loat percentage 67537678# 675376783 4
The pictorial representation of a"o(e structure memory allocation is gi(en "elo/. This diagram /ill
help you to understand the memory allocation concept in C (ery easily.
C Type Bualifiers
Prev Next
C type *ualifiers : The -ey/ords /hich are used to modify the properties of a (aria"le are called
type *ualifiers.
Types of C type *ualifiers:
There are t/o types of *ualifiers a(aila"le in C language. They are,
1. const
. (olatile
1. const -ey/ord:
Constants are also li-e normal (aria"les. .ut, only difference is, their (alues can)t "e modified "y
the program once they are defined.
They refer to fixed (alues. They are also called as literals.
They may "e "elonging to any of the data type.
:yntax:
const data&type (aria"le&name% (or) const data&type #(aria"le&name%
7lease refer C Constants topic in this tutorial for more details on const -ey/ord.
. (olatile -ey/ord:
=hen a (aria"le is defined as (olatile, the program may not change the (alue of the (aria"le
explicitly.
.ut, these (aria"le (alues might -eep on changing /ithout any explicit assignment "y the program.
These types of *ualifiers are called (olatile.
6or example, if glo"al (aria"le)s address is passed to cloc- routine of the operating system to store
the system time, the (alue in this address -eep on changing /ithout any assignment "y the
program. These (aria"les are named as (olatile (aria"le.
:yntax:
(olatile data&type (aria"le&name% (or) (olatile data&type #(aria"le&name%
C Code for .an- 2pplication
Prev Next
C code for real time .an- application program is gi(en "elo/. This program /ill perform all the "elo/
operations.
1. Creating ne/ account To create a ne/ account
. Cash Deposit To Deposit some amount in ne/ly created account
!. Cash /ithdra/al C To =ithdra/ some amount from your account
4. Display 2ccount information 't /ill display all informations of the existing accounts
A. 4og out
9. Clearing the output screen and display a(aila"le options
C Code for .an- 2pplication:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
// 9tructure declaration
struct acc_ty&e
{
char ban:_name;2<;
char ban:_branch;2<;
char acc_holder_name;=<;
int acc_number;
char acc_holder_address;1<;
"loat a>ailable_balance;
,;
struct acc_ty&e account;2<;
/*
&rint"('?he abo>e structure can be declared using
ty&ede" li:e belo@');
ty&ede" struct acc_ty&e
{
char ban:_name;2<;
char ban:_branch;2<;
char acc_holder_name;=<;
int acc_number;
char acc_holder_address;1<;
"loat a>ailable_balance;
,4cc_detail;
4cc_detail account;2<;
*/
int num_acc;
>oid (reate_ne@_account();
>oid (ash_.e&osit();
>oid (ash_@ithdra@l();
>oid 4ccount_in"ormation();
>oid %og_out();
>oid dis&lay_o&tions();
/* main &rogram */
int main()
{
char o&tion;
char "2";7< = 'htt&///"resh2re"resh.com/';
num_acc=;
@hile(1)
{
&rint"('+n***** Aelcome to 5an: 4&&lication *****+n');
&rint"('+n?his demo &rogram is brought you by 0s'-"2");
dis&lay_o&tions();
&rint"('Blease enter any o&tions (1/2/=/C/7/D) ');
&rint"('to continue / ');
o&tion = getch();
&rint"('0c +n'- o&tion);
s@itch(o&tion)
{
case )1)/ (reate_ne@_account();
brea:;
case )2)/ (ash_.e&osit();
brea:;
case )=)/ (ash_@ithdra@l();
brea:;
case )C)/ 4ccount_in"ormation();
brea:;
case )7)/ return ;
case )D)/ system('cls');
brea:;
de"ault / system('cls');
&rint"('Blease enter one o" the o&tions');
&rint"('(1/2/=/C/7/D) to continue +n ');
brea:;
,
,
return ;
,
/*Eunction to dis&lay a>ailable o&tions in this a&&lication*/
>oid dis&lay_o&tions()
{
&rint"('+n1. (reate ne@ account +n');
&rint"('2. (ash .e&osit +n');
&rint"('=. (ash @ithdra@l +n');
&rint"('C. 4ccount in"ormation +n');
&rint"('7. %og out +n');
&rint"('D. (lear the screen and dis&lay a>ailable ');
&rint"('o&tions +n+n');
,
/* Eunction to create ne@ account */
>oid (reate_ne@_account()
{
char ban:_name;2<;
char ban:_branch;2<;
char acc_holder_name;=<;
int acc_number;
char acc_holder_address;1<;
"loat a>ailable_balance = ;
""lush(stdin);
&rint"('+nFnter the ban: name / ');
scan"('0s'- 8ban:_name);
&rint"('+nFnter the ban: branch / ');
scan"('0s'- 8ban:_branch);
&rint"('+nFnter the account holder name / ');
scan"('0s'- 8acc_holder_name);
&rint"('+nFnter the account number(1 to 1)/ ');
scan"('0d'- 8acc_number);
&rint"('+nFnter the account holder address / ');
scan"('0s'- 8acc_holder_address);
strc&y(account;acc_numberG1<.ban:_name-ban:_name);
strc&y(account;acc_numberG1<.ban:_branch-ban:_branch);
strc&y(account;acc_numberG1<.acc_holder_name-
acc_holder_name);
account;acc_numberG1<.acc_number=acc_number;
strc&y(account;acc_numberG1<.acc_holder_address-
acc_holder_address);
account;acc_numberG1<.a>ailable_balance=a>ailable_balance;
&rint"('+n4ccount has been created success"ully +n+n');
&rint"('5an: name / 0s +n' -
account;acc_numberG1<.ban:_name);
&rint"('5an: branch / 0s +n' -
account;acc_numberG1<.ban:_branch);
&rint"('4ccount holder name / 0s +n' -
account;acc_numberG1<.acc_holder_name);
&rint"('4ccount number / 0d +n' -
account;acc_numberG1<.acc_number);
&rint"('4ccount holder address / 0s +n' -
account;acc_numberG1<.acc_holder_address);
&rint"('4>ailable balance / 0" +n' -
account;acc_numberG1<.a>ailable_balance);
//num_accHH;
,
// .is&laying account in"ormations
>oid 4ccount_in"ormation()
{
register int num_acc = ;
//i" (Istrcm&(customer-account;count<.name))
@hile(strlen(account;num_acc<.ban:_name)>)
{
&rint"('+n5an: name / 0s +n' -
account;num_acc<.ban:_name);
&rint"('5an: branch / 0s +n' -
account;num_acc<.ban:_branch);
&rint"('4ccount holder name / 0s +n' -
account;num_acc<.acc_holder_name);
&rint"('4ccount number / 0d +n' -
account;num_acc<.acc_number);
&rint"('4ccount holder address / 0s +n' -
account;num_acc<.acc_holder_address);
&rint"('4>ailable balance / 0" +n+n' -
account;num_acc<.a>ailable_balance);
num_accHH;
,
,
// Eunction to de&osit amount in an account
>oid (ash_.e&osit()
{
auto int acc_no;
"loat add_money;
&rint"('Fnter account number you @ant to de&osit money/');
scan"('0d'-8acc_no);
&rint"('+n?he current balance "or account 0d is 0" +n'-
acc_no- account;acc_noG1<.a>ailable_balance);
&rint"('+nFnter money you @ant to de&osit / ');
scan"('0"'-8add_money);
@hile (acc_no=account;acc_noG1<.acc_number)
{
account;acc_noG1<.a>ailable_balance=
account;acc_noG1<.a>ailable_balanceHadd_money;
&rint"('+n?he #e@ balance "or account 0d is 0" +n'-
acc_no- account;acc_noG1<.a>ailable_balance);
brea:;
,acc_noHH;
,
// Eunction to @ithdra@ amount "rom an account
>oid (ash_@ithdra@l()
{
auto int acc_no;
"loat @ithdra@_money;
&rint"('Fnter account number you @ant to @ithdra@ money/');
scan"('0d'-8acc_no);
&rint"('+n?he current balance "or account 0d is 0" +n'-
acc_no- account;acc_noG1<.a>ailable_balance);
&rint"('+nFnter money you @ant to @ithdra@ "rom account ');
scan"('0"'-8@ithdra@_money);
@hile (acc_no=account;acc_noG1<.acc_number)
{
account;acc_noG1<.a>ailable_balance=
account;acc_noG1<.a>ailable_balanceG@ithdra@_money;
&rint"('+n?he #e@ balance "or account 0d is 0" +n'-
acc_no- account;acc_noG1<.a>ailable_balance);
brea:;
,acc_noHH;
,
,utput for C code "an- 2pplication 7rogram:

You might also like