0% found this document useful (0 votes)
38 views44 pages

Memory Allocation: Subject: COMP6047 Algorithm and Programming Year: 2019

The document discusses various memory allocation techniques in C programming, including static and dynamic allocation. Static allocation assigns memory at compile time that remains for the program duration, while dynamic allocation uses functions like malloc(), calloc(), and realloc() to assign memory at runtime that can be freed. The document provides examples of declaring static variables and using dynamic allocation functions.

Uploaded by

marvelius putra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views44 pages

Memory Allocation: Subject: COMP6047 Algorithm and Programming Year: 2019

The document discusses various memory allocation techniques in C programming, including static and dynamic allocation. Static allocation assigns memory at compile time that remains for the program duration, while dynamic allocation uses functions like malloc(), calloc(), and realloc() to assign memory at runtime that can be freed. The document provides examples of declaring static variables and using dynamic allocation functions.

Uploaded by

marvelius putra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Subject : COMP6047

ALGORITHM AND PROGRAMMING


Year : 2019

Memory Allocation
Learning Outcomes
At the end of this session, student will be able to:
• Demonstrate usage of static and dynamic memory allocation in a
C program (LO2 & LO3)

COMP6047 - Algorithm and Programming 2


Sub Topics
Memory Allocation:
– Static variable
– Register variable
– External variable
– Void * data type
– Command Line Argument
– Command Execution
– Memory Concept
– Memory Allocation
– Static Memory Allocation
– Dynamic Memory Allocation
– Macro
– Pointer to Function
– C Preprocessor

COMP6047 - Algorithm and Programming 3


Static Keyword
• Keyword static can be used as variable type, or return value type of a
function
• Static variable:
– Allocated at program start and de-allocated at the end of a
program
– Default value = 0
– Scope of static variable is inside a file where the variable is defined
• Syntax:
static type variable_name;
• Example:
static int x;

COMP6047 - Algorithm and Programming 4


Static Keyword
Example of the static keyword:

static int i; //Variable accessible only from this file


static void func(); // Function accessible only from this
// file
int max_so_far( int curr ){
static int biggest; // Variable whose value is
// retained between each function
// call
if( curr > biggest ) biggest = curr;
return biggest;
}

COMP6047 - Algorithm and Programming 5


Static Variable
Example:

#include <stdio.h>

void print()
{
Output:
static int count=0; count = 0
printf("count=%d\n",count++); count = 1
}
count = 2
int main(void) count = 3
{ count = 4
int i;
for(i=0; i<5; i++) print();
count = 5
for(i=0; i<3; i++) print(); count = 7
return 0;
}

COMP6047 - Algorithm and Programming 6


Register Variable
• Objective: increase run time speed.
• Defining a variable store in a register (if possible – register is
limited). If rejected: automatic variable.
• Syntax:
register data_type variable_name;
• Example :
register int x;

COMP6047 - Algorithm and Programming 7


External Variable
• In a modular programming, a program is divided into modules.
In C modules are implemented using function.
• A module may consist of several functions. And save in a file.
• If function in a particular file wants to access a variable in other
file, then use keyword extern
• Example :
extern int x;

COMP6047 - Algorithm and Programming 8


External Variable
• Example:
#include <stdio.h> int x=12;

int main()
{
extern int x;
printf("%d\n",x);
File: data.c
return 0;
}

File : main.c

COMP6047 - Algorithm and Programming 9


External Variable
• Example: (Error)
#include <stdio.h> static int x=12;

int main()
{
extern int x;
printf("%d\n",x);
File: data.c
return 0;
}
Error!

File : main.c
Scope of a static variable is the file where it is defined.
COMP6047 - Algorithm and Programming 10
Void * Data Type
• Keyword void : Function
without actual
void main(void) parameter
{
void *malloc(size_t size);
………
}
Pointer that
A void function can point any
data type

COMP6047 - Algorithm and Programming 11


Void * Data Type
• Type void * always use type casting

• Example:
char *pstr;
int *pint;
float *pfloat;
pstr=(char *)malloc(20);
pint=(int *)malloc(20);
pfloat=(float *)malloc(20);

COMP6047 - Algorithm and Programming 12


Const Char *
• Comparing char * with const char * using strcpy
Example:
char *strcpy( char *strDestination, const char *strSource );
• Description:
– char * : should be a pointer (has an address)
– const char * : can be string or pointer
• Example:
char ss[20]; char str[20] = ”Good Morning”;
strcpy(ss,”Good Morning”);
strcpy(ss, str);
strcpy(”Hello”, ss); //error Constant String

COMP6047 - Algorithm and Programming 13


Command Line Argument
• Some time application should take input parameters from the
command line: DOS, Linux e.g.:
– copy file1 file2
– del file3

• How to get parameters: file1, file2 and file3?


– Answer: Adding parameters on the main program
– int main( int argc, char *argv[ ])

COMP6047 - Algorithm and Programming 14


Command Line Argument
• Example:
#include <stdio.h>
int main( int argc, char *argv[ ]) {
int i;
printf(“Total argument=%d\n",argc);
for(i=0; i<argc; i++) {
printf("Argument %d = %s\n",i,argv[i]);
}
return 0;
}
If the above code run from DOS command or LINUX console will result:
C>Prog argc1 argc2 argc3
Argument 0 = Prog
Argument 1 = argc1
Argument 2 = argc2
Argument 3 = argc3

COMP6047 - Algorithm and Programming 15


Command Execution
• To execute DOS or LINUX command, we can use library function
system(char *)

• Example:
#include <stdio.h>
int main(){
char str[]=“Welcome to BINUS\n";
printf(str);
system("date");Output:
Welcome to BINUS
return 0; The current date is: 08/07/2007
} Enter the new date: (dd-mm-yy)

COMP6047 - Algorithm and Programming 16


Memory Allocation
• Memory allocation:
acquiring some memory space (RAM) managed by the OS to be
used by a program.
• Memory de-allocation:
releasing memory space (RAM) back to the OS.

int main() { nim is a variable, nim needs memory


long nim; space as data store.
float gpa;
... gpa is a variable, gpa needs memory as
} data store

COMP6047 - Algorithm and Programming 17


Memory Allocation
Memory Allocation as a data store:
1. static
 can be assigned with name  variable
 allocated at compile time
 stored at local stack memory
 remain unchanged during the program run
 de-allocated when the program end
2. dynamic
 can be assigned with name
 allocated at run-time
 stored at heap memory
 can be de-allocated at any time

COMP6047 - Algorithm and Programming 18


Static Memory Allocation
struct tdata {
char nim[9];
char name[26];
float gpa;
} ;

int main () {
struct tdata data[100];
int i;
...
}

If an integer needs memory space of 4 bytes and a float 8 bytes then variable
data and i above need memory space of:
100 x (9 + 26 + 8) + 4 = 4504 byte
COMP6047 - Algorithm and Programming 19
Dynamic Memory Allocation
• Function malloc() is used to allocate one block of memory
dynamically at heap memory. An argument (actual parameter)
sent to this function is a value stating the size of allocated
memory (in byte)
• Syntax :
void * malloc (size_t size);
size: size of memory in byte.
• If allocation is successful, it will return memory address of the
memory allocated. If not (e.a: proposed malloc size larger than
existing heap memory), it will return Null.
Example: int *a;
a = (int *) malloc(sizeof(int));
COMP6047 - Algorithm and Programming 20
Dynamic Memory Allocation
• Function calloc() is used to allocate some blocks of
memory dynamically at heap memory, where each element
given size. Calloc initialized all elements with zero.
• Syntax :
void *calloc(size_t memblock,
size_t size);
size = number of byte ea block or element
memblock = number of block or element
• Example: int *a;
a = (int *)
calloc(20,sizeof(int));

COMP6047 - Algorithm and Programming 21


Dynamic Memory Allocation
• Function realloc() is used to reallocate some blocks of
memory or element dynamically at heap.
• Syntax :
void *realloc(void *ptr, size_t size);
size = number of byte each block or element
ptr = is a pointer to the address of targeted memory
location. int *a, *ptr;
• Example: a = (int *) realloc(ptr,sizeof(int));

COMP6047 - Algorithm and Programming 22


Dynamic Memory Allocation
• Function free() used to release allocated memory at heap
memory.
• Syntax: void free (void *block);
block is a pointer to a memory location (dynamic)
# include <stdio.h>
# include <stdlib.h>
int main() {
int *number1, *number2, *number3;
number1 = (int *) malloc (sizeof(int));
number2 = (int *) malloc (sizeof(int));
number3 = (int *) malloc (sizeof(int));
scanf("%d %d", number1, number2);
*number3 = *number1 * *number2;
printf("%d x %d = %d\n", *number1, *number2,
*number3);
free(number1); free(number2); free(number3);
return 1;
COMP6047 - Algorithm and Programming 23
}
Integer Memory Allocation
int *number1, *number2, *number3;
number1 = (int *) malloc (sizeof(int));
number2 = (int *) malloc (sizeof(int));
number3 = (int *) malloc (sizeof(int));

COMP6047 - Algorithm and Programming 24


Array Memory Allocation
# include <stdio.h>
# include <stdlib.h>
int main() {
int *arr, n, i;
do {
fflush(stdin);
printf(“total element ? ");
scanf("%d", &n);
if (n == 0) break;
arr = (int *) malloc (n * sizeof(int));
printf(“Input %d numbers: ", n);
for (i = 0; i < n; i++) scanf(“%d", &arr[i]);
printf(“reversed: ");
for (i = n - 1; i >= 0; i--) printf("%d ", arr[i]);
printf("\n\n");
free(arr);
}while (1);
return 1;
}
COMP6047 - Algorithm and Programming 25
Array Dynamic Memory Allocation

int *arr;
printf(“total element ? ");
scanf("%d", &n);
arr = (int *) malloc (n * sizeof(int));

total element ? 3

COMP6047 - Algorithm and Programming 26


Array Dynamic Memory Allocation
printf(“Input %d numbers: ", n);
for (i = 0; i < n; i++) scanf("%d", &arr[i]);
printf(“reversed: ");
for (i = n - 1; i >= 0; i--) printf("%d ", arr[i]);

total element ? 3
Input 3 numbers: 11 22 33
reversed: 33 22 11

COMP6047 - Algorithm and Programming 27


Array of Pointer of Dynamic Structure
# include <stdio.h>
# include <stdlib.h>

struct takad {
char nim[9];
float gpa;
} ;

int main() {
struct takad *akad[100];
int n, i;
float total = 0, rerata;
...
}

COMP6047 - Algorithm and Programming 28


Array of Pointer of Dynamic Structure

akad[i]= (struct takad*) malloc(sizeof(struct takad));

COMP6047 - Algorithm and Programming 29


Pointer of Array of Dynamic Structure
# include <stdio.h>
# include <stdlib.h>

struct takad {
char nim[9];
float gpa;
} ;

int main() {
struct takad *akad;
int n, i;
float total = 0, rerata;

COMP6047 - Algorithm and Programming 30


Macro
• Using #define
• Placed at the beginning of a code
• Its scope starts at its declaration position to the end of a
program.
• A macro is not recognized by other program.
#include <stdio.h>
#define ERROR printf("Error..\
n")
int main() {
int x=0;
int y=35;
if(x == 0) ERROR;
else y=y/x;
return 1;
}
COMP6047 - Algorithm and Programming 31
Macro
• Example using Parameter
#include <stdio.h>

#define SUM(x, y)(x+y)

int main() {
int x=10;
int y=35;
printf("%d\n",SUM(x,y));
return 1;
}

COMP6047 - Algorithm and Programming 32


Pointer to Functions
• Pointer to function is the address of a function in the memory

• Syntax:
return_type (* pointer_name)(parameter);

• Example:
int (*compare)(int a, int b);
note: compare is pointer to function name, pointing to a function
that return integer value which has 2 integer parameters

• Note the difference:


int compare (int a, int b);
Means: compare is a function name with integer return value that
has 2 integer parameters
COMP6047 - Algorithm and Programming 33
Pointer to Functions
• Example:
#include <stdio.h>
int function1(int a)
int function1(int a);
{
int function2(int b); a++;
int main() return a;
{ }
int x;
int(*f)(int); int function2(int b)
f=function1; {
x=(*f)(3); b = b * b;
printf("x=%d\n",x); return b;
f=function2; }
x=(*f)(13);
printf("x=%d\n",x);
getch();
return(0);
}
COMP6047 - Algorithm and Programming 34
C Preprocessor Directive
• Process is done before compilation.
• Preprocessor directive started with symbol #
• Example :
#include <filename>
#include ”namafile”
#define identifer replacement-text Discussed at
session 3-4
Example:
#define PHI 3.14

Preprocessor #define also used for macro

COMP6047 - Algorithm and Programming 35


C Preprocessor Directive
• Conditional Compilation
#if expression Preprocessor operator defined :
…… Syntax :
#endif defined( identifier )
defined identifier
OR
Return true (nonzero) if
#if expression identifier has been defined
…… and false (0) if not.
#else
……
#endif

COMP6047 - Algorithm and Programming 36


C Preprocessor Directive
#include <stdio.h>
#include <stdlib.h>
#define DEVC
Dev-C does not have delay()
int main()
{ as in Turbo C, but using
int i; sleep() instead.
for(i=1; i<79; i++){
gotoxy(i,10); printf(" =>");
To write a code compliable to
#if defined TURBOC both compiler, then this
delay(60); preprocessor example can be
#else used.
sleep(60);
#endif
}
getch(); This program is to be compiled inDev-C
return 0;
}
COMP6047 - Algorithm and Programming 37
C Preprocessor Directive
#include <stdio.h>
#include <stdlib.h>
#define TURBOC
int main()
{
int i;
for(i=1; i<79; i++){
gotoxy(i,10); printf(" =>");
#if defined TURBOC
delay(60);
#else
sleep(60);
#endif
}
getch();
return 0; This program is to be compiled in Turbo-C
}
COMP6047 - Algorithm and Programming 38
Exercise
1. Using <malloc.h> describe the following function!
– void *malloc ( size_t size );
– void *calloc ( size_t num, size_t size );
– void *realloc ( void *memblock, size_t size );
– void free ( void *memblock );

2. void (*ptr[3])(int)= {function1. function2,


function3};
Describe the above code!

COMP6047 - Algorithm and Programming 39


Exercise
3. Describe the following preprocessor directive:
1. #ifdef
……
#endif
2. #error
3. #pragma
4. #line
5. #ifndef
……
#endif

COMP6047 - Algorithm and Programming 40


Exercise
4. C language provides the following predefined symbolic
constant:
__LINE__
__FILE__
__DATE__
__TIME__
Describe each symbolic constant above!

5. Describe the pro-cons of using macro along with a function!

COMP6047 - Algorithm and Programming 41


Summary
• Memory allocation:
acquiring some memory space (RAM) managed by the OS to be
used by a program

• Memory de-allocation:
releasing memory space (RAM) back to the OS

COMP6047 - Algorithm and Programming 42


References
• Paul Deitel & Harvey Deitel. (2016). C how to program : with an
introduction to C++. 08. Pearson Education. Hoboken. ISBN:
9780133976892. Chapter 2, 13 & 14
• C - Storage Classes: http://
www.tutorialspoint.com/cprogramming/c_storage_classes.htm
• C Programming - Dynamic Memory allocation:
http://www.exforsys.com/tutorials/c-language/dynamic-memory
-allocation-in-c.html

COMP6047 - Algorithm and Programming 43


END

COMP6047 - Algorithm and Programming 44

You might also like