Memory Allocation in C

Size: px
Start display at page:

Download "Memory Allocation in C"

Transcription

1 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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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 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.

34 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

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. 35

36 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

37 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

38 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 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; }

40 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 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 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; }

43 Passing Command Line Arguments in C / C++ Input: C:\>sum 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

dynamic memory allocation

dynamic memory allocation Dynamic memory allocation in C The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions

More information

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

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization

More information

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

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha C Tutorial Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha CS 370 - Operating Systems - Spring 2019 1 Outline What is a pointer? & and * operators

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

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

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

C Tutorial Pointers, Dynamic Memory allocation, Makefile

C Tutorial Pointers, Dynamic Memory allocation, Makefile C Tutorial Pointers, Dynamic Memory allocation, Makefile -Abhishek Yeluri and Rejina Basnet 8/23/18 CS370 - Fall 2018 Outline What is a pointer? & and * operators Pointers with Arrays and Strings Dynamic

More information

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

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017 Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();

More information

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1 C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...

More information

MODULE V: POINTERS & PREPROCESSORS

MODULE V: POINTERS & PREPROCESSORS MODULE V: POINTERS & PREPROCESSORS INTRODUCTION As you know, every variable is a memory-location and every memory-location has its address defined which can be accessed using ampersand(&) operator, which

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility, there are four library routines known as memory management

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

MODULE 1. Introduction to Data Structures

MODULE 1. Introduction to Data Structures MODULE 1 Introduction to Data Structures Data Structure is a way of collecting and organizing data in such a way that we can perform operations on these data in an effective way. Data Structures is about

More information

Computer Programming Unit 3

Computer Programming Unit 3 POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size];

More information

Arrays, Pointers and Memory Management

Arrays, Pointers and Memory Management Arrays, Pointers and Memory Management EECS 2031 Summer 2014 Przemyslaw Pawluk May 20, 2014 Answer to the question from last week strct->field Returns the value of field in the structure pointed to by

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2010 17 October 2010 1 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. 2 1 Arrays: Example

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

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

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

MODULE 5: Pointers, Preprocessor Directives and Data Structures

MODULE 5: Pointers, Preprocessor Directives and Data Structures MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two

More information

Lecture 3: C Programm

Lecture 3: C Programm 0 3 E CS 1 Lecture 3: C Programm ing Reading Quiz Note the intimidating red border! 2 A variable is: A. an area in memory that is reserved at run time to hold a value of particular type B. an area in memory

More information

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

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Pointers. Introduction

Pointers. Introduction Pointers Spring Semester 2007 Programming and Data Structure 1 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications.

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators

More information

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?

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? Lecture 16 Functions II they re back and they re not happy Daily Puzzle If it is raining at midnight - will we have sunny weather in 72 hours? function prototypes For the sake of logical clarity, the main()

More information

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

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

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison

More information

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

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides From Java to C Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides 1 Outline Overview comparison of C and Java Good evening Preprocessor

More information

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

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems Deep C Multifile projects Getting it running Data types Typecasting Memory management Pointers Fabián E. Bustamante, Fall 2004 Multifile Projects Give your project a structure Modularized design Reuse

More information

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

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

More information

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

Key C Topics: Tutorial Pointers, Dynamic Memory allocation, Valgrind and Makefile CS370 Key C Topics: Tutorial Pointers, Dynamic Memory allocation, Valgrind and Makefile CS370 Outline Pointers in C & and * operators Pointers with Arrays and Strings Dynamic memory allocation malloc() and free()

More information

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

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

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Array Initialization

Array Initialization Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]

More information

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

First of all, it is a variable, just like other variables you studied Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

Pointers and File Handling

Pointers and File Handling 1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY

More information

Memory Allocation. General Questions

Memory Allocation. General Questions General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

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

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( ) Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough

More information

Bangalore South Campus

Bangalore South Campus USN: 1 P E PESIT Bangalore South Campus Hosur road, 1km before ElectronicCity, Bengaluru -100 Department of Basic Science and Humanities INTERNAL ASSESSMENT TEST 3 Date: 22/11/2017 Time:11:30am- 1.00 pm

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

Cpt S 122 Data Structures. Data Structures

Cpt S 122 Data Structures. Data Structures Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation

More information

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

Quick review pointer basics (KR ch )

Quick review pointer basics (KR ch ) 1 Plan for today Quick review pointer basics (KR ch5.1 5.5) Related questions in midterm Continue on pointers (KR 5.6 -- ) Array of pointers Command line arguments Dynamic memory allocation (malloc) 1

More information

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

Pointers review. int a = 5; int *ptr = &a; cout << *ptr; Pointers review Let a variable aa be defined as int *aa;, what is stored in aa? Let a variable aa be defined as int ** aa; what is stored in aa? Why we should NOT return a pointer to a local variable?

More information

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

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 1. Do a page check: you should have 8 pages including this cover sheet. 2. You have 50 minutes

More information

CSE 333 Lecture 2 Memory

CSE 333 Lecture 2 Memory CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking

More information

University of Kelaniya Sri Lanka

University of Kelaniya Sri Lanka University of Kelaniya Sri Lanka Scope, Lifetime and Storage Class of a Variable COSC 12533/ COST 12533 SACHINTHA PITIGALA 2017 - Sachintha Pitigala < 1 What is Scope? Scope of Identifier: The scope of

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 FUNCTIONS INTRODUCTION AND MAIN All the instructions of a C program are contained in functions. üc is a procedural language üeach function performs a certain task A special

More information

[0569] p 0318 garbage

[0569] p 0318 garbage A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the

More information

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

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Dynamic Memory Dynamic Memory Allocation Strings September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Pointer arithmetic If we know the address of the first element of an array, we can compute the addresses

More information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship

More information

POINTER AND ARRAY SUNU WIBIRAMA

POINTER AND ARRAY SUNU WIBIRAMA POINTER AND ARRAY SUNU WIBIRAMA Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation Basic Pointer 3 Pointers A pointer is a reference to another variable (memory location) in a program

More information

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

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2 CMPT 125 Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance John Edgar 2 Edit or write your program Using a text editor like gedit Save program with

More information

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

Language comparison. C has pointers. Java has references. C++ has pointers and references Pointers CSE 2451 Language comparison C has pointers Java has references C++ has pointers and references Pointers Values of variables are stored in memory, at a particular location A location is identified

More information

Functions & Memory Maps Review C Programming Language

Functions & Memory Maps Review C Programming Language Functions & Memory Maps Review C Programming Language Data Abstractions CSCI-2320 Dr. Tom Hicks Computer Science Department Constants c 2 What Is A Constant? Constant a Value that cannot be altered by

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 6: Recursive Functions. C Pre-processor. Cristina Nita-Rotaru Lecture 6/ Fall 2013 1 Functions: extern and static Functions can be used before they are declared static for

More information

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

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24 Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program

More information

Memory (Stack and Heap)

Memory (Stack and Heap) Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03

More information

C PROGRAMMING Lecture 5. 1st semester

C PROGRAMMING Lecture 5. 1st semester C PROGRAMMING Lecture 5 1st semester 2017-2018 Program Address Space The Stack The stack is the place where all local variables are stored a local variable is declared in some scope Example int x; //creates

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

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

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet High-performance computing and programming Intro to C on Unix/Linux IT Uppsala universitet What is C? An old imperative language that remains rooted close to the hardware C is relatively small and easy

More information

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

CSci 4061 Introduction to Operating Systems. Programs in C/Unix CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,

More information

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

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and

More information

EM108 Software Development for Engineers

EM108 Software Development for Engineers EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

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

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

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

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

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

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011 Functions in C Lecture Topics Introduction to using functions in C Syntax Examples Memory allocation for variables Lecture materials Textbook 14.1-14.2, 12.5 Homework Machine problem MP3.2 due March 18,

More information

Fundamentals of Programming Session 12

Fundamentals of Programming Session 12 Fundamentals of Programming Session 12 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

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

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0; 1. Short answer questions: (a) Compare the typical contents of a module s header file to the contents of a module s implementation file. Which of these files defines the interface between a module and

More information

int Return the number of characters in string s.

int Return the number of characters in string s. 1a.String handling functions: Function strcmp(const char *s1, const char *s2) strcpy(char *s1, const char *s2) strlen(const char *) strcat(char *s1, Data type returned int Task Compare two strings lexicographically.

More information

Data Structure Series

Data Structure Series Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after

More information

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

COMP3221: Microprocessors and. and Embedded Systems. Overview. Variable Types and Memory Sections. Types of Variables in C COMP3221: Microprocessors and Embedded Systems Lecture 12: Functions I http://www.cse.unsw.edu.au/~cs3221 Lecturer: Hui Wu Session 2, 2005 Overview Variable types Memory sections in C Parameter passing

More information

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

UNIT III (PART-II) & UNIT IV(PART-I) UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System

More information

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

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

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

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

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

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to

More information

C programming basics T3-1 -

C programming basics T3-1 - C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of

More information

Variation of Pointers

Variation of Pointers Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before

More information

Lecture 2: C Programm

Lecture 2: C Programm 0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes

More information

Functions. Chapter 5

Functions. Chapter 5 Functions Chapter 5 Function Definition type function_name ( parameter list ) declarations statements For example int factorial(int n) int i, product = 1; for (i = 2; I

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

C Programming Language

C Programming Language Department of Electrical, Electronics, and Communication Engineering C Programming Language Storage Classes, Linkage, and Memory Management Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department

More information

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION My Training Period: hours Note: gcc compilation examples are given at the end of this Module. Abilities: Understand and use the auto, register,

More information

Lecture 14. Dynamic Memory Allocation

Lecture 14. Dynamic Memory Allocation Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 14-1 Lecture 14. Dynamic Memory Allocation The number of variables and their sizes are determined at compile-time before a program runs /*

More information

Course organization. Course introduction ( Week 1)

Course organization. Course introduction ( Week 1) Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

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

int marks[10]; // fixed size and fixed address No change in Memory address. Dynamic Memory Allocation : Used When we want to allocate memory during run time. int marks[10]; // fixed size and fixed address No change in Memory address. // fixed size. ( no change in size possible

More information