[go: up one dir, main page]

0% found this document useful (0 votes)
56 views43 pages

Dynamic Memory 1

Dynamic memory allocation in C++ allows memory to be allocated and freed at runtime using operators new and delete. Memory is allocated from the free store, which may be implemented similarly to a heap. The new operator allocates memory and returns a pointer, while delete frees the memory. Structures allow grouping of heterogeneous data types and defining custom data types. Memory alignment and padding may increase the size of structures beyond the sum of member sizes.

Uploaded by

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

Dynamic Memory 1

Dynamic memory allocation in C++ allows memory to be allocated and freed at runtime using operators new and delete. Memory is allocated from the free store, which may be implemented similarly to a heap. The new operator allocates memory and returns a pointer, while delete frees the memory. Structures allow grouping of heterogeneous data types and defining custom data types. Memory alignment and padding may increase the size of structures beyond the sum of member sizes.

Uploaded by

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

Getting started with C++

Dynamic Memory Allocation, Typecasting, struct, union, typedef, enum

Dr. K. Veningston
Department of Computer Science and Engineering
National Institute of Technology Srinagar
veningstonk@nitsri.ac.in
Dynamic Memory Allocation
• In C,
– Using malloc(), calloc(), realloc(), free().
– Dynamically allocated memory is allocated on Heap.
• The free section in memory called heap is implemented as heap data structure.
• In heap, searching and inserting is faster. The free storage is implemented as heap.
• In C++,
– Using new, delete operator (allotted in free store) when we want to
allocate memory dynamically at runtime.
– We are not sure by what means this free storage is implemented.
• So, they named it Free store.
• Difference between heap and free store? There is no thin line.
Dynamic Memory Allocation (DMA)
• DMA in C++ refers to performing memory allocation manually by
programmer.
• Dynamically allocated memory is allocated on Heap.
• Applications:
– Variable length arrays at runtime.
– Linked Lists, Trees, Graphs, etc.
• For normal variables, memory is allocated and deallocated automatically.
• For dynamically allocated memory, it is our responsibility to deallocate
memory when no longer needed.
– If we do not do it explicitly, a memory leak happens.
Dynamic Memory Allocation
• Dynamic Memory Allocation in C is using malloc(), calloc(), free(), realloc().
• C++ supports these functions and has two operators new and delete that
perform the task of allocating and freeing the memory in a easier way.
– We will use new and delete instead of these functions.
– When we use new and delete, the part of the storage from where the memory is
allocated is called Free Store.
• This Free Store might/might not be implemented as Heap.
• It is compiler implementation dependent.
• Operator new acquires its memory by calling an operator new().
• Similarly, operator delete frees its memory by calling an operator delete().
new Operator
• new operator requests for memory allocation on the Free
Store.
– If sufficient memory is available, new operator initializes the memory
and returns the address of the newly allocated and initialized
memory to the pointer.
ptr = new data_type;
• Example:
int *ptr = NULL;
ptr = new int; //This returns a pointer to the memory
location that is of size int (allocates 4
bytes of memory from Free Store).
Free Store vs. Heap?
• Documentation does not clearly mention the internal details
and main differences.
new Operator
• When new needs memory on the free store for an object of
type X, it calls the operator.
new (sizeof(X));

• Similarly, when new needs memory on the free store for an


array of N objects of type X, it calls the operator.
// Use this if you want a continuous
new[] (N * sizeof(X)); block/chunk of memory like an array.
We are dynamically creating array in //This allocates memory from free store
memory. int *p = new int[10]; for 10 continuous integers i.e. 40 bytes and
returns the starting address of this array.
delete Operator
• It is our responsibility to deallocate dynamically allocated memory.
– If you forget to delete the allocated memory, memory leak happens.

delete ptr;
delete[] ptr;
– What is memory leak?
• Anyhow when the program ends, OS will free the memory.
• But, there are some programs which runs indefinitely on servers, where if we are
continuously using new and not using delete may cause memory leak.
Practice Questions
• How to create a dynamic array of integers of size 3 using new
in C++?
int *arr = new int[3];

• How to create a dynamic array of pointers to integers of size 3


using new in C++?
int **arr = new int*[3];
Find output?
Find output?

Dangling Pointer?
Find output?
Typecasting (same as in C)
• Typecasting is making a variable of one type, such as an int, act
like another type, a char, for one single operation.
• To typecast something, put the type of variable you want the
actual variable to act as inside parenthesis in front of the actual
variable.

// 66 will be treated as a largest


datatype in which it can fit in i.e.
long long.
A special type of typecasting in C++ that is not
supported in C
• In C++, we use this syntax as well.

cout << (char) 66 <<endl;

(or)

cout << char (66) <<endl; //Readable


Implicit type conversion in C++
• If we do not do typecasting, the C++ compiler does this for us.
• C++ supports other types of typecasts as well.
– Smaller data type to Largest data type.
– bool  char  short int  int  unsigned int  long  unsigned  long long  float 
double  long double
• Data loss can occur (signs, overflow)
• Example:
– If we try to evaluate (int + unsigned int), the compiler will see that unsigned int > int and treats
both as unsigned int and do the operation leading to data loss (sign is lost).

Implicit type conversion by the Compiler Explicit type conversion by the Programmer
Find the output?
• Endianness An int is stored using 4 bytes (4 chunks of 8 bits each)

– Big-endian MSB
100 101 102
LSB
103
• Most Significant Byte (MSB) in the least
address
LSB MSB
– Little-endian 100 101 102 103

• Least Significant Byte (LSB) in the least


address
• For typecasting, we must understand how int is stored in memory.
– When we typecast int into char, the char can hold only 1 byte.
– Which 1 byte of 4 bytes this char will point to?
Find the output?
• Output of little-endian system
The binary of int 257 in 4 bytes will be (00000000 00000000 00000001 00000001)2

1 1 0 0
00000001 00000001 00000000 00000000
LSB MSB
100 101 102 103

• Output of big-endian system


0 0 1 1
00000000 00000000 00000001 00000001
MSB LSB
100 101 102 103

Little-endian system outputs ‘b’


Big-endian system outputs ‘a’
Structures
• Array vs. Structures
– Array is a sequence of elements of homogeneous datatype.
– Structure is a sequence of elements of arbitrary/heterogeneous
datatypes.
• User-defined datatype
– Address is a datatype.
Structures - Example

A variable of type Address.


a1 will have all these
properties
Structures
• How to reference the structure members/elements?
– Using . (dot) operator
– Through pointers using -> (struct pointer dereference) operator

Pointer to struct Address


Structures
• What is the sizeof(a1)?
– In C,
• The sum of sizes of all the elements present in the structure.
– In C++,
• It is different. We have padding and packing.

name
door_number padding
street
packing town

zip
Structures
• Total size of the structure is not always the sum of the sizes of
all structure data members in C++.
• Example:
struct Readout {
char hour; padding
int value;
char seq; padding
};

– The size of Readout on a 4-byte-int machine would be 12 bytes and


not 6 bytes.
• This is due to the padding added by the compiler to avoid alignment issues.
Structure Member Alignment
Assume it is run in a 32-bit machine
• In C++, the size of the
structure A is not 3 bytes.
• 32-bit computer architecture
can read 32-bit information in
1 memory cycle i.e.
comfortable in reading 4
bytes at a time.
– Therefore, it avoids the
overflow.
Structure Member Alignment
• The compiler avoids this type of situation.
int a; //takes 4 bytes


100 100 101 102 103
If int stores at address 103, then it
104 104 105 106 107
requires 2 memory cycles to read
108
112
this int.

• Instead, it stores 1st byte at 104 3 bytes of data. If we want to store


another int, memory will not be allocated
… from 103. Instead, it will be allotted from
100 100 101 102 103 104. so that, it is stored in contiguous 4
bytes of memory. It can now be read in 1
104 104 105 106 107
memory cycle.
108
112 This is called padding. This
… byte will be useless.
Structure Member Alignment – Example 1
Assume it is run in a 32-bit machine
• In C++, the size of the structure
A is not 3 bytes.
• 32-bit computer architecture
can read 32-bit information in 1
memory cycle i.e. comfortable
in reading 4 bytes at a time.
– Therefore, it avoids the overflow.
• It pads 1 byte here by seeing that

100 101
the next element is of type short
100 struct A oa;
104
char a
104
pad 1 byte
105
102

106
short int b
103

107
int. Thus, this entire data fits in 4
108 bytes.
112

Structure Member Alignment – Example 2
• The size of the structure B is
Assume it is run in a 32-bit machine

not 7 bytes.


100 101
100 char a pad 1 byte
102
short int b
103
104 105 106 107
struct B ob;
104 int c
108
112

Structure Member Alignment – Example 3
• The size of the structure B is
Assume it is run in a 32-bit machine

not 13 bytes.
– The memory will be allocated
sequentially in the order in
which we have declarations.
– The overall memory alignment

of the structure is as given.
100
100
char a
101
pad 7 bytes
102 103
• Why padding here?
104 105 106 107
104
108 109 110 111
108 struct C oc;
double b
112 112 113 114 115

116 116 117 int c 118 119

120 120 121 pad 4 bytes 122 123


Structure Member Alignment – Example 4
• What if we create? …
100 101 102 103
100 char a pad 7 bytes
struct C oc[10]; 104
104 105 106 107

108 109 110 111


108
double b struct C oc[0];
112 112 113 114 115
int c
116 116 117 int c 118 119

120 120
120 121
121 122
122 123
123 Architecture avoids this kind
char a
124 of overflows.
124 125 126 127
128 128 129 130 131 struct C oc[1];
132 132 133 134 135
136 136 137 138 139

140
144
148

NOTE: The size of any structure will be multiple of the largest datatype present in it.
Structure Member Alignment – Example 4
• What if we create? …
100 101 102 103
100 char a pad 7 bytes
struct C oc[10]; 104
104 105 106 107

108 109 110 111


108
double b struct C oc[0];
112 112 113 114 115

116 116 117 int c 118 119

120 120 121 pad 4 bytes 122 123

124 124 125 126 127


char a
pad 7 bytes
128 128 129 130 131
132
132 133
double b
134 135 struct C oc[1];
136
136 137 138 139
140 140 141 int c 142 143
144 144 145pad 4 bytes 146 147

148

NOTE: The size of any structure will be multiple of the largest datatype present in it. But not all the time.
Structure Member Alignment – Example 5
• The size of struct D is not 24.
• Shrunk the memory wherever appropriate.
• Print the content of this structure byte by byte
and see what happens.


100 101 102 103
100 char a pad 3 bytes
104 105 106 107
104 int b
108 109 110 111
struct D od;
108
double c
112 112 113 114 115

116 116 117 118 119

120 120 121 122 123


NOTE
• The contents of struct C and struct D are the same.
– But the size of struct C is 24 bytes and the size of struct D is 16 bytes.
• The size of the structure depends on the order in which the
members are defined.
– Ideally, if you want to save memory, either put the structure
members on the decreasing order of their size or put them all on the
increasing order of their size.
• The size of the structure is always by the divisible by the size of
the largest datatype present in it.
Structure Member Alignment – Example 6 & 7

… …
100 101 102 103 100 101 102 103
100 int x
100
double y
104 105 106 107 104 105 106 107
104 pad 4 bytes 104
108 109 110 111 108 109 110 111
108 108 int x
double y
112 112 113 114 115 112 112 short int z 113 114 pad 2 bytes115

116 116 short int z 117 118 119 116 116 117 118 119
pad 7 bytes
120 120 121 122 123 120 120 121 122 123
Unions
• A union is a struct in which all members are allocated at the
same address so that the union occupies only as much space
as its largest member.
– Same as struct, but only the size of the maximum datatype which is
present in it is basically allotted.
• It can only hold value for one member at a time.
– Only one of the members of a union will be alive at a time, not all of
them. The last initialized value will be alive.
Unions
• Example:

street is not alive

Memory alignment of a Union

state[20]
padding
Unions
• The size of the union does not vary. It is the same as in C.
• The size of the union will be the size of the largest member
present in the union itself.
– The size of a union is taken according to size of the largest member in
it.
typedef
• typedef stands for “type definition”
• The typedef keyword allows us to create new names for types such
as int or more commonly in C++, template types.
• Examples:
– typedef long long int lli; //instead of long long int, we can use lli.
• lli will now be an alias for the datatype long long int.
– typedef struct A sA; //instead of struct A, we can use sA.
• sA will now be an alias for the structure type A.
• If we do not use typedef with structures, every time we create an object of a
structure, we have to tell the compiler that A is a structure.
typedef - Example

C++ does not require the use of typedef when declaring a struct, hence the warning.
typedef – Output of this code?
Enumerations
• It is also like structure and union.
• An enum is a type that can hold a set of integer values specified by the user.
– It can only take values of certain type (i.e. homogeneous)
• These values are defined at the time of declaring the enumerated type.
• Example:

Default initialization

– Here, red, green, and blue are called the enumerators with implicit values as 0, 1 and 2
respectively.
Enumerations
• We can also change the default value of an enum element at
the time of declaration.
• Example:

Default initialization

– Here, red, green, and blue have values as 10, 20 and 30 respectively.
Enumerations
• Why enums are used?
– An enum variable takes only one value out of all possible values. This
makes enum a good choice to work with flags.
enum - Example
• Find the output?

You might also like