Memory Allocation in C

Similar documents
dynamic memory allocation

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

C Tutorial Pointers, Dynamic Memory allocation, Makefile

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

MODULE V: POINTERS & PREPROCESSORS

Dynamic Memory Allocation

Dynamic memory allocation (malloc)

Procedural programming with C

MODULE 1. Introduction to Data Structures

Computer Programming Unit 3

Arrays and Pointers (part 1)

Arrays, Pointers and Memory Management

Arrays and Pointers (part 1)

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Dynamic memory allocation

In Java we have the keyword null, which is the value of an uninitialized reference type

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Lecture 3: C Programm

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Pointers. Introduction

Understanding Pointers

211: Computer Architecture Summer 2016

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Subject: Fundamental of Computer Programming 2068

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Key C Topics: Tutorial Pointers, Dynamic Memory allocation, Valgrind and Makefile CS370

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Kurt Schmidt. October 30, 2018

Array Initialization

First of all, it is a variable, just like other variables you studied

CS 11 C track: lecture 5

CS201- Introduction to Programming Current Quizzes

Pointers and File Handling

Memory Allocation. General Questions

Chapter 2. Procedural Programming

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Bangalore South Campus

High Performance Programming Programming in C part 1

Cpt S 122 Data Structures. Data Structures

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Quick review pointer basics (KR ch )

Pointers review. int a = 5; int *ptr = &a; cout << *ptr;

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

CSE 333 Lecture 2 Memory

University of Kelaniya Sri Lanka

PROGRAMMAZIONE I A.A. 2017/2018

[0569] p 0318 garbage

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Programming. Pointers, Multi-dimensional Arrays and Memory Management

POINTER AND ARRAY SUNU WIBIRAMA

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Language comparison. C has pointers. Java has references. C++ has pointers and references

Functions & Memory Maps Review C Programming Language

CSCI 171 Chapter Outlines

CS201 Some Important Definitions

CS240: Programming in C

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Memory (Stack and Heap)

C PROGRAMMING Lecture 5. 1st semester

EL2310 Scientific Programming

Pointers, Dynamic Data, and Reference Types

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

Programs in memory. The layout of memory is roughly:

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Fundamental of Programming (C)

o Code, executable, and process o Main memory vs. virtual memory

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

Fundamentals of Programming Session 12

CA341 - Comparative Programming Languages

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

int Return the number of characters in string s.

Data Structure Series

COMP3221: Microprocessors and. and Embedded Systems. Overview. Variable Types and Memory Sections. Types of Variables in C

UNIT III (PART-II) & UNIT IV(PART-I)

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

ch = argv[i][++j]; /* why does ++j but j++ does not? */

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C programming basics T3-1 -

Variation of Pointers

Lecture 2: C Programm

Functions. Chapter 5

Memory Management. CSC215 Lecture

C Programming Language

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION

Lecture 14. Dynamic Memory Allocation

Course organization. Course introduction ( Week 1)

Content. In this chapter, you will learn:

int marks[10]; // fixed size and fixed address No change in Memory address.

Transcription:

Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called code segment) is where the compiled machine code of the program resides containing machine instructions to be carried out by the CPU. The remaining two areas of memory, (i.e., the stack and heap segments) are where storage may be allocated by the compiler for data storage. These areas are also called data segment. 1

Memory Allocation in C heap can be thought of as the segment of memory occupying the bottom of the data segment and growing upwards, while the stack, another segment of memory occupying the top of the data segment and growing downward. When regular variables are declared inside functions and those functions are called, C creates the variables of those functions on the stack by pushing down the stack pointer. After those functions return (exit), C pops up the variables of those functions from the stack (i.e., the variables are de-allocated from memory). 2

Memory Allocation in C This push-pop operations are performed automatically in LIFO (Last In, First Out) pattern, i.e., the variables of the last returning (exiting) function is de-allocated first, then the variables of the second to last returning function are de-allocated and so on. For this automatic memory management, The size of stack-allocated memory must always be known at compilation. However, in some programs, it might be necessary to use variables / arrays with an unknown size at compilation to provide for user-defined array size during runtime. Under the circumstances, one must allocate the memory dynamically during runtime, on the heap 3

Memory Allocation in C C allows programmers to allocate and release heap memory during runtime. Note that if one continues to allocate heap memory space without freeing it in a program, the program could eventually crash. So heap memory must be freed by the programmer explicitly since heap memory is not managed automatically like stack memory. In order to allocate as well as free heap memory, library functions are available which should be used inside the program. 4

Dynamic Memory Allocation in C Although, C language inherently does not has any technique to allocate memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory (i.e., heap memory) allocation. malloc( ) calloc( ) free() realloc() Allocates requested size of bytes and returns a pointer first byte of allocated space Allocates space for an array elements, initializes to zero and then returns a pointer to memory Dellocate the previously allocated space Change the size of previously allocated space 5

malloc( ) The name malloc stands for "memory allocation". The function malloc() reserves a block of memory (heap) of specified size and return a pointer of type void which can be casted into pointer of any form. Syntax: pointer_name = (cast-type*)malloc(byte-size); Here, pointer_name is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer. Example: ptr = (int*)malloc(100*sizeof(int)); This statement will allocate either 200 bytes according to size of int 2 bytes and the ptr points to the address of first byte of memory. The variables then can be accessed as *ptr, *(ptr+1), *(ptr+2),...*(ptr+99). 6

calloc( ) The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory (heap) each of same size and sets all bytes to zero. Syntax: pointer_name = (cast-type*)calloc(n, element-size); This statement will allocate contiguous space in memory (heap) for an array of n elements. Example: ptr = (float*)calloc(25, sizeof(float); This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. The variables can be accessed by *ptr, *(ptr+1), *(ptr+2).*(ptr+24). 7

free( ) Dynamically allocated memory (heap) with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release memory space. Syntax: free (pointer_name ); This statement cause the space in memory (heap) pointed by pointer_name to be deallocated. 8

realloc( ) If the previously allocated memory (heap) is insufficient or more than sufficient, then memory size can be changed using realloc(). Syntax: realloc (pointer_name, new_size ); Here, pointer_name is reallocated with size of newsize. 9

Example-1 /* C program to find sum of n elements entered by user. Using malloc() funcion*/ #include <stdio.h> #include <stdlib.h> int main(){ int n,i,*ptr,sum=0; printf("enter number of elements: "); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); if(ptr==null){ printf("error! memory not allocated."); exit(0);} 10

Example-1 printf("enter elements of array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("sum=%d",sum); free(ptr); return 0; } 11

Example-2 /* C program to find sum of n elements entered by user. Using calloc() funcion*/ #include <stdio.h> #include <stdlib.h> int main(){ int n,i,*ptr,sum=0; printf("enter number of elements: "); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); if(ptr==null){ printf("error! memory not allocated."); exit(0);} 12

Example-2 printf("enter elements of array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("sum=%d",sum); free(ptr); return 0; } 13

Example-3 /* C program using realloc() funcion*/ #include <stdio.h> #include <stdlib.h> int main(){ int *ptr,i,n1,n2; printf("enter size of array: "); scanf("%d",&n1); ptr=(int*)malloc(n1*sizeof(int)); printf("address of previously allocated memory: "); 14

Example-3 for(i=0;i<n1;++i) printf("%u\t",ptr+i); printf("\nenter new size of array: "); scanf("%d",&n2); ptr=realloc(ptr,n2); for(i=0;i<n2;++i) printf("%u\t",ptr+i); return 0; } 15

Storage Classes There are four storage class specifiers auto register static extern The storage class precedes the variable s declaration and instructs the compiler how the variable should be stored Items declared with auto or register specifier have local lifetimes while those declared with the static or extern specifier have global lifetimes 16

Storage Classes The four storage class specifiers affect the visibility of a variable or function, as well as its storage class Visibility (sometimes defined as scope of a variable) refers to that portion of the source program in which the variable or function can be referenced by name The placement of a variable or function declaration within a source file also affects storage class and visibility The exact meaning of each storage class specifier depends on whether the declaration appears at the external or internal level, and whether the item being declared is a variable or a function 17

Storage Classes Variable declarations at the external level may only use the static or extern storage classes They are either definitions of variables or references to variables defined elsewhere An external variable declaration that also initializes the variable (implicitly or explicitly) is a defining declaration: static int iv1 = 16; // explicit static int iv1; // implicit 0 by default int iv2 = 20; Once a variable is defined at the external level, it is visible throughout the rest of the source file in which it appears 18

Storage Classes One can define a variable at the external level only once within a source file If one gives the static storage class specifier, he/she can define another variable with the same name and the static storage class specifier in a different source file; since each static definition is visible only within its own source file, no conflict occurs The extern storage class specifier declares a reference to a variable defined elsewhere One can use an extern declaration to make visible a definition in another source file, or to make a variable visible above its definition in the same source file The variable is visible throughout the remainder of the source file in which the declared reference occurs 19

Storage Classes For an extern reference to be valid, the variable it refers to must be defined once, and only once, at the external level The definition can be in any of the source files that form the program // Source file A #include <stdio.h> void a (void); void b (void); extern int iv; // makes iv visible above its dec. 20

Storage Classes int main () { iv++; // uses the above extern reference printf ("%d\n", iv); // prints 11 a (); return 0; } int iv = 10; // actual definition of iv void a (void) { iv++; printf ("%d\n", iv); // prints 12 b (); } 21

Storage Classes // Source file B #include <stdio.h> extern int iv; // references iv declared in Source A void b (void) { } iv++; printf ("%d\n", iv); // prints 13 One can use any of the four storage class specifiers or variable declarations at the internal level (the default is auto) 22

Storage Classes The auto storage class specifier declares a variable with a local lifetime It is visible only in the block in which it is declared and can include initializers The register storage-class specifier tells the compiler to give the variable storage in a register, if possible It speeds access time and reduces code size It has the same visibility as the auto variable If no registers are available when the compiler encounters a register declaration, the variable is given auto storage class and stored in memory 23

Storage Classes A variable declared at the internal level with the static storage class specifier has a global lifetime but is visible only within the block in which it is declared Unlike auto variables, static variables keep their values when the block is exited One can initialize a static variable with a constant expression it is initialized to 0 by default A variable declared with the extern storage class specifier is a reference to a variable with the same name defined at the external level in any of the source files of the program 24

Create a Multi-file C Program (Project) A multi-file C program is a C program whose codes (functions) are distributed into more than one file. For example, a C program might consist of 4 files namely, main.c, f1.c, f2.c and f3.c For a single C program distributed among multiple files, it must be ensured that there is one and only main() function in one of the files preferably in main.c In codeblocks, in order to code, compile and build a multi-file C program, one might start a project of C program and keep adding files in the project using the menu driven dialog boxes. After coding is done in all files, just save the project, then compile and build. The program will be ready to run. 25

Multi-file C Program /* Create a project in codeblocks containing main.c,then add files file1.c and file2.c)*/ #include <stdio.h> /* main.c */ #include myheader.h int main(){ int a = 5, b = 15; //optional float gpa[5]={3.95, 3.87, 3.77, 3.75, 3.65}; printf("\n\nthe sum of two integers is %d", AddInt(5, 15)); printf("\n\nbefore swapping a and b, a = %d, b = %d", a, b); swap(&a, &b); printf("\n\nafter swapping a and b, a = %d, b = %d", a, b); printf("\n\nthe average GPA is = %f", avg_gpa(gpa, 5)); printf("\n\nthe factorial of a is = %ld", factorial(8)); return 0;} 26

Multi-file C Program /* C program using multi-files (project)*/ /* file1.c */ int AddInt(int x, int y){ return x + y;} void swap(int *x, int *y){ int temp; temp = *x; *x = *y; *y = temp; } 27

Multi-file C Program /* C program using multi-files (project)*/ float avg_gpa(float *x, int c){ /* file2.c */ int i; float sum = 0.0; for(i = 0; i <= c; i++) sum = sum + *(x+i); return sum/c;} long factorial(int n){ long fact = 1; int i; for(i=1; i <= n; i++) fact = fact * i; return fact;} 28

Create a Header File A header file (e.g., myheader.h) can be created using codeblocks by clicking new, file, C/C++ header file and giving it a name. This file contains all the prototype declarations of functions from all the files and is usually included in the main.c as follows: #ifndef MYHEADER_H /* myheader.h */ #define MYHEADER_H int AddInt(int x, int y); void swap(int *x, int *y); float avg_gpa(float *x, int c); long factorial(int n); #endif 29

Create and Distribute User Library of Functions A user library of functions can be distributed as the source code without the main() function, containing the file1.c, file2.c and the myheader.h files. However, usually the library of functions are distributed as object code (filename.o) archives as libfilename.a. In codeblock, in order to create archives of object-type library of functions, one has to start a project of static library, add multiple files if necessary, type the code, then compile and build. Upon building, an archive of object versions of all the files is created with the name libfilename.a inside the project folder. This libfilename.a along with the header file is usually distributed as a third-party library for reuse in a C program. 30

Create User Library of Functions /* Start a new project myfuncs of static library and add a file file1.c as shown below */ int AddInt(int x, int y){ return x + y;} /* file1.c */ void swap(int *x, int *y){ int temp; temp = *x; *x = *y; *y = temp; } 31

Create User Library of Functions /* Add another file file2.c to myfuncs project */ float avg_gpa(float *x, int c){ /* file2.c */ int i; float sum = 0.0; for(i = 0; i <= c; i++) sum = sum + *(x+i); return sum/c;} long factorial(int n){ long fact = 1; int i; for(i=1; i <= n; i++) fact = fact * i; return fact;} 32

33 Create and Distribute User Library of Functions Upon compiling and then building, an archive of the name libmyfuncs.a inside the project folder is created. This archive contains object versions of all the files in the project myfuncs namely main.o, file1.o and file2.o. Next a header file (e.g., myfuncs.h) is created using the same steps as described earlier. This file should contain all the prototype declarations of functions from all the files in this static library project. This libmyfuncs.a along with the header file myfuncs.h can now be distributed as a third-party library for reuse in a C program.

How to use User Library of Functions /* Create a new empty file named test_myfuncs.c */ #include <stdio.h> /* test_myfuncs.c */ #include myfuncs.h int main(){ int a = 5, b = 15; float gpa[5]={3.95, 3.87, 3.77, 3.75, 3.65}; printf("\n\nthe sum of two integers is %d", AddInt(5, 15)); printf("\n\nbefore swapping a and b, a = %d, b = %d", a, b); swap(&a, &b); printf("\n\nafter swapping a and b, a = %d, b = %d", a, b); printf("\n\nthe average GPA is = %f", avg_gpa(gpa, 5)); printf("\n\nthe factorial of a is = %ld\n\n", factorial(8)); return 0; } 34

Use User Library of Functions In order to use an object archive of user library of functions (also called third-party library) in a C program such as in test_myfuncs.c, the user has to include the supplied header file with the library as follows: #include myfuncs.h The user should also copy the header file and the archive file inside the program folder. Then in codeblocks, the user has to go to settings, compiler, linker settings, click add and browse the location of the archive file libmyfuncs.a to select it. Once selected, the user can use the user library functions according to the prototype declarations in the supplied header file into his/her program and can compile, build and run the program. 35

Use User Library of Functions In order to use an object archive of user library of functions (also called third-party library) in a C program such as in test_myfuncs.c, the user has to include the supplied header file with the library as follows: #include myfuncs.h The user should also copy the header file and the archive file inside the program folder. Then in codeblocks, the user has to go to settings, compiler, linker settings, click add and browse the location of the archive file libmyfuncs.a to select it. Once selected, the user can use the user library functions according to the prototype declarations in the supplied header file into his/her program and can compile, build and run the program. 36

Use User Library of Functions The output of the test_myfuncs.c program is shown above which uses the header file myfuncs.h and the user library of functions libmyfuncs.a. 37

Passing Command Line Arguments in C / C++ When executing a program in either C or C++ there is a way to pass command line arguments to the function main(). Two types of arguments are passed: argc an integer variable indicating the total number of parameters argv[] an array of strings containing the Parameters Arguments are always passed as character strings. Numbers must be converted from characters (strings) to integers, floats, doubles, etc. Each parameter is separated by a space. If a parameter (string) itself contains a space then it should be passed using double quotes. 38

39 Passing Command Line Arguments in C / C++ #include <stdio.h> int main(int argc, char *argv[]) { int i = 0; printf( \n\ttotal No. of Arguments: %d, argc); for (i=0; i<argc; i++) printf( \n\targument #argv[%d] is --> %s, i, argv[i]); return 0; }

Passing Command Line Arguments in C / C++ Input: C:\>hello Each word is a separate argument [must be executed from a command prompt window/linux shell/terminal with correct path to the executable file hello.exe ] Output: Total No. of Arguments: 6 Argument #argv[0] is -->hello Argument #argv[1] is -->Each Argument #argv[2] is -->word Argument #argv[3] is -->is Argument #argv[4] is -->a Argument #argv[5] is -->separate argument 40

41 Passing Command Line Arguments in C / C++ Arguments are always passed to main( ). There must be two: first is an integer, i.e., int argc second char pointer to an array, i.e., char *argv[] First argument (argv[0]) will always be the name of the calling program. argc will always be at least 1 The first argument is always argv[0] The last argument is always argv[argc-1] argv[argc] will always be a null pointer

42 Passing Command Line Arguments in C / C++ #include <stdio.h> int main(int argc, char *argv[]) { int i, sum = 0; printf( \n\ttotal No. of Arguments: %d, argc); for (i = 1; i < argc; i++) sum = sum + atoi (argv[i]); printf( \n\tsum of the %d numbers = %d\n, i-1, sum); return 0; }

Passing Command Line Arguments in C / C++ Input: C:\>sum 3 5 10 20 25 Output: [must be executed from a command prompt window/linux shell/terminal with correct path to the executable file sum.exe ] In codeblocks, to pass command-line arguments to the main() function, one has to make a project of console application. Then from the menu select project set programs arguments program arguments, put the argument strings excluding the program name. The program then runs with the supplied arguments passing to the function main(). 43