Lesson 4 struct and memory management
|
|
- Isaac Hunt
- 5 years ago
- Views:
Transcription
1 Introduction to Computer and Program Design Lesson 4 struct and memory management James C.C. Cheng Department of Computer Science National Chiao Tung University
2 enum l Enumerators Grouping the constant integers enum LEVEL{ LV_EASY, LV_MID, LV_HARD, LV_GOD }; Don t forget the semicolon enum LEVEL lv; // In C++, the keyword enum is not neccesary lv = LV_EASY; cout << lv << endl; // 0 lv = LV_GOD; cout << lv << endl; // 3 lv = LEVEL::LV_HARD; cout << lv << endl; // 2 lv = 1; // Error lv = (LEVEL)1; // lv = LEVEL::LV_MID; cout << lv << endl; // 1 enum LEVEL lv2 = LV_GOD; // The follwing statements cause compiler errors in C++ lv+=1; ++lv; lv = lv + LV_MID; lv = lv + lv2; 2
3 enum l Enumerators enum LEVEL{ LV_EASY = 2, LV_MID, LV_HARD = 10, LV_GOD, LV_NORMAL = 0, LV_ULTIMATE }; enum LEVEL lv = LV_MID; printf("%d\n", lv); // 3 lv = LV_GOD; printf("%d\n", lv); // 11 lv = LV_ULTIMATE; printf("%d\n", lv); // 1 3
4 Struct l Consider a situation as follows: float BMI(float w_kg, float h_m){ return (w_kg / (h_m * h_m); } #define MAX_N 3 char* name [MAX_N][8] = {0}; float w [MAX_N] = {0.0f}, float h [MAX_N] = {0.0f}; int n = 0, i=0; We have to use three do{ // Input the personal information independent data printf("name:");scanf("%s", &name[n]); array to record the if(name[n][0]>0){ personal information printf("weight(kg):"); scanf("%f", &w[n]); printf("height(m):"); scanf("%f", &h[n]); getchar(); ++n; } else break; }while(n < MAX_N); // Showing the personal information and calculating the BMI for(i=0; i<n; ++i) printf("[%d]name:%s, w:%f, h:%f, BMI:%f\n", i, name[i], w[i], h[i], BMI(w[i], h[i])); 4
5 Struct l The struct can help us to group many data items to descript a complicated object struct Person{ char name[8]; float w, h; }; struct Person A[MAX_N]; // In C++, the keyword struct is not neccesary do{ // Input the personal information memset(a[n].name, 0, 8); // Clear the string printf("name:");scanf("%s", A[n].name); if(a[n].name[0]>0){ printf("weight(kg):"); scanf("%f", &A[n].w); printf("height(m):"); scanf("%f", &A[n].h); getchar();++n; } else break; }while(n < MAX_N); // Showing the personal information and calculating the BMI for(i=0; i<n; ++i) printf("[%d]name:%s, w:%f, h:%f, BMI:%f\n", i, A[i].name, A[i].w, A[i].h, BMI(A[i].w, A[i].h)); 5
6 Struct l Member selection operator x.m x is an object of a data type T m is a name of a member of T p->m p is a pointer m is a name of a member of T struct Person x; // In C++, the keyword struct is not neccesary sprintf(x.name, "James"); x.w = 65.0f; x.h = 1.785f; // Using. operator to access each member struct Person* px = &x; // In C++, the keyword struct is not neccesary printf("name:%s, w:%f, h:%f, BMI:%f\n", px->name, px->w, px->h, BMI(px->w, x->h)); // Using -> operator to access each member 6
7 Struct l If you want to pass an argument of a struct, you should pass its address or reference DO NOT use call-by-value to pass a struct to a function! void SetPerson(struct Person* px, const char *name, float w, float h){ sprintf(px->name, "%s", name); px->w = w; px->h = h; } void SetPerson(struct Person x, const char *name, float w, float h){ sprintf(x.name, "%s", name); x.w = w; x.h = h; } void PrintPerson(const struct Person* px){ printf("name:%s, w:%f, h:%f, BMI:%f\n", px->name, px->w, px->h, BMI(px->w, px->h)); } SetPerson(&x, "Bill", 90.0f, 2.0f); PrintPerson(&x); 7
8 Struct l Word alignment How many byte does a struct occupy? struct Person{ char name[8]; float w, h; }; printf("%d\n", sizeof(struct Person)); // 16= struct Point3D{ int x, y, z; }; printf("%d\n", sizeof(struct Point3D)); // 12 Byte struct EmptyBox{ }; printf("%d\n", sizeof(struct EmptyBox)); // 0 byte in C, but 1 byte in C++ 8
9 Struct l Word alignment struct Person{ char gender; char name[8]; float w, h; // M : Male; F : Female }; printf("%d\n", sizeof(struct Person)); // Is the answer 17? struct Person{ char gender; // M : Male; F : Female char name[8]; float w, h; short age; }; printf("%d\n", sizeof(struct Person)); // Is the answer 19? struct Person{ char gender; // M : Male; F : Female char name[8]; short age; float w, h; }; printf("%d\n", sizeof(struct Person)); // Is the answer 19? 9
10 Struct l Word alignment Word: The unit of memory accessing 4 byte in 32-bit systems; 8 byte in 64-bit systems Alignment: For efficient memory accessing, some holes are added in a struct to satisfy the memory addressing. address Data struct Person{ char gender; char name[8]; float w, h; short age; }; Word 1 Word 2 Word 3 Word 4 Word 5 Word 6 Holes 10
11 Struct l Word alignment How to disable word alignment? Using the #prgma pack #pragma pack(push, 1) // change to 1 byte alignment and store the original setting struct Person{ }; #pragma pack(pop) // restore the original setting printf("%d\n", sizeof(struct Person)); // 19 byte address Data struct Person{ char gender; char name[8]; float w, h; short age; }; Word 1 Word 2 Word 3 Word 4 Word 5 11
12 Struct l Bit filed We can access each bit of member variable in a struct The member variables must be integers struct Port{ unsigned short data:8; unsigned short address:4; unsigned short flaga:1; unsigned short flagb:1; unsigned short flagc:1; unsigned short flagd:1; }; // A B C D Addr(4 bit) Data (8 bit) struct Port io; unsigned short *pn = (unsigned short *)&io; *pn = 0; // Initialization io.data = 0xFF; io.flagd = 1; printf("%d\n", *pn); // = = 0x x00FF 12
13 Struct l Struct assignment The datatype of l-value & r-value must be the same The struct should contain no any dynamic-size member Person x1, x2; sprintf(x1.name, "James"); x1.w = 65.0f; x1.h = 1.785f; x2 = x1; x2.w = 80.0f; PrintPerson(&x1); // James, 65.0, PrintPerson(&x2); // James, 80.0,
14 Struct l Dynamic-size member struct Person{ char* name; float w, h; }; void InPerson(struct Person* px){ char buf[256] = {0}; if(px->name) free(px->name); // Release data px->name = NULL; printf("name:"); scanf("%s", buf); if(buf[0] > 0){ px->name = (char *)calloc(1, strlen(buf)+1 ); sprintf(px->name, "%s", buf); printf("weight(kg):"); scanf("%f", &px->w); printf("height(m):"); scanf("%f", &px->h); getchar(); } } struct Person A[MAX_N]; memset(a, 0, sizeof(struct Person) * MAX_N); // Clear all data do{ // Input the personal information InPerson(&A[n]); if(a[n].name) ++n; else break; }while(n < MAX_N); // Showing the personal information and calculating the BMI for(i=0; i<n; ++i) PrintPerson(&A[i]); 14
15 Struct l Dynamic-size member We need to design a function to copy a Person void CopyPerson(struct Person* px1, const struct Person* px2){ if(px1->name) free(px1->name); px1->name = NULL; if(px2->name ){ px1->name = (char *)calloc(1, strlen( px2->name ) + 1 ); sprintf(px1->name, "%s", px2->name ); px1->w = px2->w; px1->h = px2->h; } } What if we copy a Person by the assignment operator? Person x1, x2 InPerson(&x1); x2 = x1; x1.name[0] = X ; PrintPerson(&x1); PrintPerson(&x2); //? 15
16 Struct l Initialization Initializer list Student x = {0};! Student y = {"James", 75.2f, 175.6f};! // Notice the order! struct Student{! char name[8];! float w, h;! };! Uniform initialization C++11 and GCC Visual C , 2012 not support Student x{0};! Student y{"james", 75.2f, 175.6f};! // Notice the order! 16
17 Union l A union object can contain only one of its members at a time. l The size of the union is at least the size of the largest member. union NewInt{ int nvalue; unsigned char btvalue[4]; }; NewInt x; x.nvalue = 256; printf("%x, %X, %X, %X\n", x.btvalue[0], x.btvalue[1], x.btvalue[2], x.btvalue[3]); // 0, 1, 0, 0 printf("%d\n", sizeof(x)); // 4 byte 17
18 Union l It usually combines union and struct in most cases union Vector3D{ double data[3]; struct{double x, y, z;}; struct{double r, g, b;}; struct{double u, v, w;}; }; printf( %d\n, sizeof(union Vector3D)); // 24 byte union Vector3D vec; vec.x = 0; vec.y = 10, vec.b = 30; printf( %f, %f, %f\n, vec.u, vec.v, vec.w); for(i=0;i<3; ++i) printf( %f,, vec.data[i]); 18
19 Dynamic memory allocation l malloc Syntax: #include <stdlib.h> void* malloc( size_t n ); where the size_t is the same as unsigned int malloc() returns a pointer to a chunk of memory of n bytes, or NULL if there is an error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you are done with it. The returned pointer must be typecast l free Syntax: #include <stdlib.h> void free( void* ptr ); free() deallocates the space pointed to by ptr, freeing it up for future use. ptr must be NULL or used in a previous call to malloc(), otherwise a runtime error will occur on free(). 19
20 Dynamic memory allocation l calloc Syntax: #include <stdlib.h> void* calloc (size_t unit, size_t n ); calloc() returns a pointer to a chunk of memory of unit * n bytes with elements initialized t zero, or NULL if there is an error. The returned pointer must be typecast 20
21 Dynamic memory allocation l Example: char *pc = (char *)malloc(10); // 10 characters int *pi = (int *)malloc(sizeof(int) * 10); // 10 integers double *pd = (double *)malloc(80); // 10 doubles if( pc!= NULL && pi!= NULL && pd!= NULL){ // Check the allocation for(int i=0; i<10; ++i) pd[i] = pi[i] = pc[i] = i + 65; for(int i=0; i<10; ++i) printf("%c, %d, %f\n", pc[i], pi[i], pd[i]); // A~J } free(pc); free(pi); free(pd); l free a NULL pointer int *p; // Non-NULL free(p); // Runtime error! p = NULL; free(p); // OK! 21
22 Dynamic memory allocation int n = 1024 * 1024 * 128; // 128 MB double rtime; clock_t clk0, clk1; char *pc = (char *)malloc(n); // clk0 = clock(); for(int i=0; i<n; ++i) pc[i] = 0; clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("iterative clearing time: %f\n", rtime); // The time is proportional to n free(pc); clk0 = clock(); pc = (char *)calloc(1,n); // re-allocating with initialization clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("calloc time: %f\n", rtime); // it's constant time if the hardware supports calloc free(pc); 22
23 Dynamic memory allocation l Memory leaks and dangling Normal allocation Pointer Memory Pointer Memory leaks Memory Pointer Memory dangling Memory 23
24 Dynamic memory allocation l Memory Leaks There is no any pointer to point a allocated memory space Executing the system monitor to watch the memory usage Using two threads to execute the following program If the memory usage approach to the limitation, just stop the program char key = 0, end = 0; do{ // Create 64M byte for input buffer int n = 1024 * 1024 * 64; char *pc =(char *)malloc(n); memset(pc, 0, n); // Clear all data scanf("%s", pc); key = pc[0]; end = pc[1]; }while(key!= 'q' && key!='q' end!= 0); If the OS does not provide Garbage Collection, the allocated memory will never be released. Notice that the timing for releasing by garbage collection is when the program has been terminated. 24
25 Dynamic memory allocation l Memory Dangling A pointer points an unallocated memory space char *pc; *pc = 100; // Dangling pc = (char *)malloc(12); int *pi = (int *)pc; free(pi); *pc = 50; // Dangling 25
26 Dynamic memory allocation l Memory Manipulation Functions memset, memory setting: #include <memory.h> or #include <string.h> void* memset( void *dest, int c, size_t count ); Ø dest: the destination pointer Ø c: set the value, c & 0xFF, to each byte of dest Ø count: the number of byte to set Ø returns the value of dest int n = 3; int *p = (int *)malloc(sizeof(int)*n); memset(p, 0, sizeof(int)*n); for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); memset(p, 255, sizeof(int)*n); for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); memset(p, 65537, sizeof(int)*n); for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); memset((int *)memset(p, 0, 12) + 1, 255, 4) ; for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); 26
27 Dynamic memory allocation l Memory Manipulation Functions The needed time of memset int n = 1024 * 1024 * 128; // 128 MB double rtime; clock_t clk0, clk1; char *pc = (char *)malloc(n); clk0 = clock(); for(int i=0; i<n; ++i) pc[i] = 0; clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("iterative clearing time: %f\n", rtime); // The needed time is proportional to n clk0 = clock(); memset(pc, 0, n); clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("memset time: %f\n", rtime); /* The needed time is still proportional to n but less than iterative method */ free(pc); 27
28 Dynamic memory allocation l Memory Manipulation Functions memcpy, memory copy: #include <memory.h> or #include <string.h> void* memcpy(void *dest, const void *src, size_t count ); dest: the destination pointer src: the source pointer count: the number of byte to copy returns the value of dest If the source and destination overlap, this function does not ensure that the original source bytes in the overlapping region are copied before being overwritten. char s1[] = "Hello! My friend!"; // Why use char[]? const char *s2 = "Hi! Guys."; // Why use const char*? memcpy(s1+7, s2+4, 6); printf("%s\n", s1); // Hello! Guys. memcpy(s1+5, s1+7, 4); printf("%s\n", s1); // Maybe HelloGuysys., maybe not 28
29 Dynamic memory allocation l Memory Manipulation Functions memmove, memory move: #include <string.h> void *memmove( void *dest, const void *src, size_t count ); dest: the destination pointer src: the source pointer count: the number of byte to move returns the value of dest It is similar to memcpy, but memmove ensures the copy of overlapping region. char s1[] = "; memcpy(s1 + 2, s1, 5); printf("%s\n", s1); //
30 Dynamic memory allocation l Memory Manipulation Functions memcmp, memory compare: #include <memory.h> or #include <string.h> int memcmp( const void *buf1, const void *buf2, size_t n ); Ø buf1 and buf2: the pointers of memory Ø n: the number of byte to compare Ø Return Value: relationship of first n bytes of buf1 and buf2 < 0: buf1 less than buf2 0: buf1 identical to buf2 > 0: buf1 greater than buf2 char first[] = " "; char second[] = " "; printf( %d\n, memcmp( first, second, 19 ) ); // 0 printf( %d\n, memcmp( first, second, 20 ) ); // -1 printf( %d\n, memcmp( first + 2, second, 18 ) ); // 1 30
31 Dynamic memory allocation l Dynamic multi-dimension array int m=0, n=0,i,j; scanf("%d %d", &m, &n); int **pp = (int **)malloc(sizeof(int *) * m); for(i=0; i<m; ++i) pp[i] = (int *)malloc(sizeof(int) * n); for(i=0; i<m; ++i) for(j=0; j<n; ++j) pp[i][j] = i * 10 + j; for(i=0; i<m; ++i){ for(j=0; j<n; ++j) printf("%2d, ", pp[i][j]); printf("\n"); } /* Do not forget to free the allocated memory in reverse order of dimension */ for(i=0; i<m; ++i) free(pp[i]); free(pp); 31
32 Linked Lists l Linked List It consists of a sequence of data items such that in each item there is a pointer or a reference to link the next item. The memory addresses of elements may not be adjacent struct Node{ int data; Node *next; }; Node* NewNode(int data){ Node *p = (Node *)calloc(sizeof(node), 1); p->data = data; return p; } Node *phead = NewNode(0), *p = phead; for( int i=1; i<5; ++i, p = p->next) data next p->next = NewNode(i); // Creating the list p = phead; while(p!= NULL) { printf("%d\n", p->data); Node *ptmp = p; p = p->next; free(ptmp); // Release each item } 32
33 Linked Lists l Doubly-Linked List Each node has two pointers, one points the next node and the other points the previous node. struct Node{ int data; Node *next, *prev;}; Node* NewNode(int data){ Node *p = (Node *)calloc(sizeof(node), 1); } p->data = data; return p; Node *phead = NewNode(0); Node *p = phead; for( int i=1; i<5; ++i, p = p->next){ p->next = NewNode(i); p->next->prev = p; } while(p!= NULL) { printf("%d\n", p->data); Node *ptmp = p; p = p->prev; } p = phead; while(p!= NULL) { printf("%d\n", p->data); Node *ptmp = p; p = p->next; free(ptmp); // Release }
34 Arrays vs. Linked Lists l Performances Random access Push back Array: O(1) Dynamic Array: O(1) Doubly-Linked list: O(n) Doubly-Linked list: O(1) Random insertion Pop back Array: O(n) Dynamic Array: O(1) Doubly-Linked list: Doubly-Linked list: O(1) Search time + O(1) Random remove Push front Dynamic Array: O(n) Array: O(n) Doubly-Linked list: O(1) Doubly-Linked list: Search time + O(1) Pop front Dynamic Array: O(n) Doubly-Linked list: O(1) where n is the number of data elements 34
35 Arrays vs. Linked Lists l Performances Resize (from n to m) Array: O(m) Doubly-Linked list: O(m) Clear Array: O(n) n m Copy assignment Array: O(n) Doubly-Linked list: O(n) = Doubly-Linked list: O(n) Concatenation Array: O(n) Doubly-Linked list: O(1) Swap Array: O(n) Doubly-Linked list: O(1) 35
Memory Management and
Introduction to Computer and Program Design Lesson 6 Memory Management and File I/O James C.C. Cheng Department of Computer Science National Chiao Tung University Dynamic memory allocation l malloc Syntax:
More informationMemory Management and
Introduction to Computer and Program Design Lesson 5 Memory Management and File I/O James C.C. Cheng Department of Computer Science National Chiao Tung University Dynamic memory allocation l malloc Syntax:
More informationObject-Oriented Programming (1)
Introduction to Computer and Program Design 2 Lesson 3 Object-Oriented Programming (1) James C.C. Cheng Department of Computer Science National Chiao Tung University What is OOP? Object-Oriented Programming
More informationMemory 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 informationPrinciples of C and Memory Management
COMP281 Lecture 9 Principles of C and Memory Management Dr Lei Shi Last Lecture Today Pointer to Array Pointer Arithmetic Pointer with Functions struct Storage classes typedef union String struct struct
More informationComputer 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 informationCOP 3223 Introduction to Programming with C - Study Union - Fall 2017
COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................
More informationKurt 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 informationLecture 8 Dynamic Memory Allocation
Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable
More informationProgramming. 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 informationPointers, 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 informationDynamic 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 informationFrom 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 informationCSC 1600 Memory Layout for Unix Processes"
CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
More informationCS201 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 informationC Structures & Dynamic Memory Management
C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail
More informationDynamic 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 informationCSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation
... 1/30 CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation Alice E. Fischer October 23, 2015 ... 2/30 Outline Storage Class Dynamic Allocation in C Dynamic Allocation in C++
More informationPRINCIPLES OF OPERATING SYSTEMS
PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)
More informationIn 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 informationMemory. 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 informationCOP 3223 Introduction to Programming with C - Study Union - Spring 2018
COP 3223 Introduction to Programming with C - Study Union - Spring 2018 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................
More informationClass Information ANNOUCEMENTS
Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to
More informationMemory 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 informationIMPORTANT 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 informationECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.
ECE 264 Exam 2 6:30-7:30PM, March 9, 2011 I certify that I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise you will receive a 1-point penalty.
More informationELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition
ELEC / COMP 177 Fall 2012 Some slides from Kurose and Ross, Computer Networking, 5 th Edition Prior experience in programming languages C++ programming? Java programming? C programming? Other languages?
More informationHigh 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 informationFinal Intro to C Review
Final Exam Content: Final Intro to C Review - Pass by reference Functions - General Syntax - Structures - Recursion(maybe?) - Programming by nature is cumulative so any past material is up for grabs as
More informationDynamic Allocation in C
Dynamic Allocation in C C Pointers and Arrays 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically,
More informationOutline. 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 informationunsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables
Graded assignment 0 will be handed out in section Assignment 1 Not that bad Check your work (run it through the compiler) Factorial Program Prints out ENTERING, LEAVING, and other pointers unsigned char
More informationCOP 3223 Introduction to Programming with C - Study Union - Fall 2017
COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................
More informationQuick 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 informationPOINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory
More informationAdvanced Pointer Topics
Advanced Pointer Topics Pointers to Pointers A pointer variable is a variable that takes some memory address as its value. Therefore, you can have another pointer pointing to it. int x; int * px; int **
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationProcedural Programming & Fundamentals of Programming
Procedural Programming & Fundamentals of Programming Exercise 3 (SS 2018) 29.05.2018 What will I learn in the 4. exercise Pointer (and a little bit about memory allocation) Structure Strings and String
More informationPointers (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 informationAPS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size
APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =
More informationQ1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100
ECE 2035(A) Programming for Hardware/Software Systems Fall 2013 Exam Three November 20 th 2013 Name: Q1: /8 Q2: /30 Q3: /30 Q4: /32 Total: /100 1/10 For functional call related questions, let s assume
More informationadvanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef
today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation
More informationDAY 3. CS3600, Northeastern University. Alan Mislove
C BOOTCAMP DAY 3 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh and Pascal Meunier s course at Purdue Memory management 2 Memory management Two
More informationCSCI-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 informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationCOSC345 Software Engineering. The Heap And Dynamic Memory Allocation
COSC345 Software Engineering The Heap And Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines Virtual memory Swapping
More informationMemory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science
Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly
More informationINDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator EXAMINATION ( End Semester ) SEMESTER ( Spring ) Roll Number Section Name Subject Number C S 1 0 0 0 1 Subject Name Programming
More informationArrays, 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 informationFundamental 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 informationint 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 informationDynamic memory. EECS 211 Winter 2019
Dynamic memory EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/06dynamic.tgz tar zx $ cd 06dynamic 3 Oops! I made a mistake. In C, the declaration struct circle read_circle();
More informationDynamic 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 informationBSM540 Basics of C Language
BSM540 Basics of C Language Chapter 4: Character strings & formatted I/O Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture To explain the input/output functions printf()
More informationCompiling and Running a C Program in Unix
CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name
More informationo 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 informationCOMP 2355 Introduction to Systems Programming
COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Pointers Pointers denote addresses in memory In C types, the * represents the use
More informationDynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan
More informationMemory 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 informationC 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 informationMODULE 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 informationStructures, Unions, and Enumerations
Chapter 16 Structures, Unions, and Enumerations 1 Structure Variables The properties of a structure are different from those of an array. The elements of a structure (its members) aren t required to have
More informationC BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.
C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,
More informationMain Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University
C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types
More informationChapter 2 (Dynamic variable (i.e. pointer), Static variable)
Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= #
More informationStandard I/O in C and C++
Introduction to Computer and Program Design Lesson 7 Standard I/O in C and C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Standard I/O in C There three I/O memory buffers
More informationArrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]
(November 10, 2009 2.1 ) Arrays An array is a collection of several elements of the same type. An array variable is declared as type array name[size] I The elements are numbered as 0, 1, 2... size-1 I
More informationM3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE
M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be
More informationPointers, Arrays, and Strings. CS449 Spring 2016
Pointers, Arrays, and Strings CS449 Spring 2016 Pointers Pointers are important. Pointers are fun! Pointers Every variable in your program has a memory location. This location can be accessed using & operator.
More informationVariables Data types Variable I/O. C introduction. Variables. Variables 1 / 14
C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition
More informationProgramming Language B
Programming Language B Takako Nemoto (JAIST) 7 January Takako Nemoto (JAIST) 7 January 1 / 13 Usage of pointers #include int sato = 178; int sanaka = 175; int masaki = 179; int *isako, *hiroko;
More information11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {
This document contains the questions and solutions to the CS107 midterm given in Spring 2016 by instructors Julie Zelenski and Michael Chang. This was an 80-minute exam. Midterm questions Problem 1: C-strings
More informationOregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 2. Spring 2016
Oregon State University School of Electrical Engineering and Computer Science CS 261 Recitation 2 Spring 2016 Outline Programming in C o Headers o Structures o Preprocessor o Pointers Programming Assignment
More informationCSC 270 Survey of Programming Languages. What is a Pointer?
CSC 270 Survey of Programming Languages C Lecture 6 Pointers and Dynamic Arrays What is a Pointer? A pointer is the address in memory of a variable. We call it a pointer because we envision the address
More informationCOMPSCI 210 Part II Data Structure
Agenda & Reading COMPSCI 210 Part II Data Structure Based on slides @ McGraw-Hill Agenda: Enum structs Nested structs Array of structs structs Parameters & Returning structs structs Pointers Exercises:
More informationMemory Organization. The machine code and data associated with it are in the code segment
Memory Management Memory Organization During run time, variables can be stored in one of three pools : 1. Stack 2. Global area (Static heap) 3. Dynamic heap The machine code and data associated with it
More informationC 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 informationC Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:
C Programming Code: MBD101 Duration: 10 Hours Prerequisites: You are a computer science Professional/ graduate student You can execute Linux/UNIX commands You know how to use a text-editing tool You should
More informationThe University of Nottingham
The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, AUTUMN SEMESTER 2009-2010 C/C++ for Java Programmers Time allowed TWO hours Candidates may complete the front cover of their answer
More informationedunepal_info
facebook.com/edunepal.info @ edunepal_info C interview questions (1 125) C interview questions are given with the answers in this website. We have given C interview questions faced by freshers and experienced
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationEL2310 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 informationCS360 Midterm 1 - February 21, James S. Plank. Put all answers on the answer sheet. In all of these questions, please assume the following:
CS360 Midterm 1 - February 21, 2017 - James S. Plank Put all answers on the answer sheet. In all of these questions, please assume the following: Pointers and longs are 4 bytes. The machine is little endian
More informationComputer Programming: Skills & Concepts (CP) Strings
CP 14 slide 1 Tuesday 31 October 2017 Computer Programming: Skills & Concepts (CP) Strings Ajitha Rajan Tuesday 31 October 2017 Last lecture Input handling char CP 14 slide 2 Tuesday 31 October 2017 Today
More informationBasis and Practice in Programming Lab 9
Basis and Practice in Programming Lab 9 User defined data structure Consists of one or more basic data type struct point // declaring a structure named as point int x; int y; // a member of the structure
More informationRecitation #11 Malloc Lab. November 7th, 2017
18-600 Recitation #11 Malloc Lab November 7th, 2017 1 2 Important Notes about Malloc Lab Malloc lab has been updated from previous years Supports a full 64 bit address space rather than 32 bit Encourages
More informationArrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)
1 Arrays General Questions 1. What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A. The element will be set to 0. B. The compiler would
More informationCS 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 informationC Characters and Strings
CS 2060 Character handling The C Standard Library provides many functions for testing characters in ctype.h. int isdigit(int c); // is c a digit (0-9)? int isalpha(int c); // is c a letter? int isalnum(int
More informationC Programming Basics II
C Programming Basics II Xianyi Zeng xzeng@utep.edu Department of Mathematical Sciences The University of Texas at El Paso. September 20, 2016. Pointers and Passing by Address Upon declaring a variable,
More informationMemory Management in C (Dynamic Strings) Personal Software Engineering
Memory Management in C (Dynamic Strings) Personal Software Engineering Memory Organization Function Call Frames The Stack The call stack grows from the top of memory down. sp Available for allocation The
More informationCS1100 Introduction to Programming
CS1100 Introduction to Programming Sorting Strings and Pointers Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Lexicographic (Dictionary) Ordering Badri
More informationCS Programming In C
CS 24000 - Programming In C Week Seven: More on memory operations, and structures. Union, function pointer, and bit operations Zhiyuan Li Department of Computer Science Purdue University, USA 2 Academic
More informationHuawei Test 3. 1 A card is drawn from a pack of 52 cards. The probability of getting a queen of club or a king of heart is:
Huawei Test 3 1 A card is drawn from a pack of 52 cards. The probability of getting a queen of club or a king of heart is: ( )1 /13 ( )2 /13 ( )1 /26 ( )1 /52 Here, n(s) = 52. Let E = event of getting
More informationCS 261 Data Structures. Introduction to C Programming
CS 261 Data Structures Introduction to C Programming Why C? C is a lower level, imperative language C makes it easier to focus on important concepts for this class, including memory allocation execution
More informationa data type is Types
Pointers Class 2 a data type is Types Types a data type is a set of values a set of operations defined on those values in C++ (and most languages) there are two flavors of types primitive or fundamental
More informationComputer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];
Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data
More informationC Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review
CS 2060 Variables Variables are statically typed. Variables must be defined before they are used. You only specify the type name when you define the variable. int a, b, c; float d, e, f; char letter; //
More informationLecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?
Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static
More information