Pointers and dynamic memory - stack vs heap

mycodeschool
23 Feb 201317:25

Summary

TLDRThis script delves into the architecture of memory, explaining the four segments of a program's memory: the instruction, global variable, stack, and heap segments. It clarifies the fixed nature of the first three and the dynamic, expandable nature of the heap, crucial for large data storage and flexible memory management. The tutorial covers the use of dynamic memory in C and C++ through functions like malloc, calloc, realloc, free, and operators new and delete, emphasizing the importance of manual memory management to prevent leaks and overflow.

Takeaways

  • 🧠 Memory is a crucial resource in computing, and understanding its architecture is vital for programmers.
  • 🏗️ A program's memory is typically divided into four segments: instruction, global variables, function calls and local variables (stack), and heap.
  • 📚 The text segment holds the program's instructions, while the global segment stores static or global variables accessible throughout the application's lifetime.
  • 📈 The stack segment manages function calls, local variables, and has a fixed size that does not grow during the application's runtime.
  • 🔄 The heap segment is a flexible memory pool that can grow and shrink during the application's lifetime, used for dynamic memory allocation.
  • 📝 In the provided C program example, the 'main' function and other functions like 'Square of Sum' and 'Square' demonstrate how memory is allocated and managed during execution.
  • 🔑 The call stack is a LIFO (Last In, First Out) structure where the most recent function call is at the top and execution pauses until it returns.
  • 🚫 Stack overflow occurs when the call stack exceeds its reserved memory, leading to a program crash, often due to infinite recursion.
  • 🛠️ Dynamic memory allocation using the heap allows for more flexibility in memory usage, but requires manual management to avoid memory leaks.
  • 🔄 In C, memory on the heap is allocated with 'malloc' and deallocated with 'free', while in C++, 'new' and 'delete' operators are used for the same purpose.
  • 🔒 It's important for programmers to be cautious with heap memory to prevent overuse and ensure proper deallocation when memory is no longer needed.

Q & A

  • What are the four segments of memory in a typical architecture?

    -The four segments of memory in a typical architecture are the text segment for storing instructions, the global variable segment for static or global variables, the stack for function calls and local variables, and the heap for dynamic memory allocation.

  • What is the purpose of the stack in memory management?

    -The stack is used to store information about function calls, including local variables and where to return after the function finishes executing. It is allocated during runtime and has a fixed size that does not grow during the application's execution.

  • Why is the heap different from the other memory segments?

    -The heap is different because its size can vary during the lifetime of the application. Unlike the stack, the heap does not have a set rule for allocation or deallocation, and a programmer can control the memory usage from the heap as needed.

  • What is the relationship between the call stack and the stack segment of memory?

    -The call stack is a concept that represents the order of function calls during program execution. The stack segment of memory is the physical area where the call stack is implemented, storing local variables and function call information.

  • What is the potential issue with using a large amount of memory on the stack?

    -Using a large amount of memory on the stack can lead to stack overflow if the call stack grows beyond the reserved memory for the stack, causing the program to crash.

  • How does dynamic memory allocation with the heap differ from memory allocation on the stack?

    -Dynamic memory allocation with the heap allows for flexible memory usage where the size can grow and shrink as needed, and the programmer has control over when to allocate and deallocate memory. Memory on the stack is automatically allocated and deallocated with function calls and has a fixed size.

  • What are the four functions used for dynamic memory allocation in C?

    -The four functions used for dynamic memory allocation in C are malloc, calloc, realloc, and free.

  • What is the purpose of the malloc function in C?

    -The malloc function is used to allocate a specified amount of memory on the heap and returns a pointer to the starting address of the allocated block.

  • What is the significance of the free function in C?

    -The free function is used to deallocate memory that was previously allocated with malloc, preventing memory leaks and unnecessary consumption of memory resources.

  • What are the two operators used for dynamic memory allocation in C++?

    -The two operators used for dynamic memory allocation in C++ are new and delete, which are type-safe and simplify memory allocation and deallocation compared to C's malloc and free.

  • Why is it important to free memory allocated on the heap?

    -It is important to free memory allocated on the heap to avoid memory leaks and to ensure efficient use of memory resources. Unlike the stack, memory on the heap does not get automatically deallocated when the function that allocated it completes.

Outlines

00:00

📚 Understanding Memory Architecture and Dynamic Memory in C/C++

This paragraph introduces the fundamental concepts of memory architecture, focusing on how operating systems and programming languages manage memory. It explains the division of a program's memory into four segments: the text segment for instructions, the global variable segment for static variables, the stack for function calls and local variables, and the heap for dynamic memory allocation. The explanation includes a simple C program example to illustrate how these segments are used during program execution, particularly highlighting the stack frame and the call stack. The paragraph also touches on the limitations of stack memory, such as fixed size and scope, and introduces the heap as a flexible, programmer-controlled memory segment.

05:03

🔄 The Stack and Heap: Limitations and Dynamic Memory Allocation

The second paragraph delves deeper into the stack's limitations, such as the inability to grow during runtime and the risk of stack overflow due to excessive recursion or deep function calls. It contrasts the stack with the heap, which is a dynamic memory segment that can expand and contract as needed. The heap allows for more flexible memory management, enabling the programmer to allocate and deallocate memory as required. The paragraph also clarifies the difference between the heap as a memory segment and the heap data structure, emphasizing that the heap's role in memory management is distinct from its implementation as a data structure.

10:06

🛠️ Mastering Dynamic Memory Allocation with malloc, calloc, realloc, and free in C

This paragraph provides an in-depth look at dynamic memory allocation in C, detailing the use of the malloc, calloc, realloc, and free functions. It explains how malloc is used to request memory from the heap and return a pointer to the allocated block, as well as the importance of typecasting the returned void pointer to the appropriate data type. The paragraph also discusses the necessity of manually freeing memory using free to avoid unnecessary memory consumption. It illustrates the process with code examples, demonstrating how to allocate memory for an integer and an array, and the importance of error handling when malloc fails to allocate memory.

15:09

🚀 Transitioning to C++: Using new and delete for Dynamic Memory Management

The final paragraph shifts the focus to C++ and its approach to dynamic memory allocation using the new and delete operators. It contrasts this with the C-style functions malloc and free, highlighting the type safety and simplicity of the new and delete operators, which eliminate the need for typecasting. The paragraph provides examples of how to allocate and deallocate memory for a single integer and an array in C++, emphasizing the ease of use and the importance of proper memory management to prevent memory leaks. It concludes with a teaser for upcoming lessons that will cover more on dynamic memory allocation and related library functions.

Mindmap

Keywords

💡Memory

Memory refers to the hardware components that store information for immediate use by a computer program or system. In the context of the video, memory is crucial for understanding how a computer operates, as it is divided into segments that serve different purposes, such as storing instructions, variables, and function calls. The script discusses how memory is managed and accessed by programmers, emphasizing the importance of memory architecture in program execution.

💡Dynamic Memory

Dynamic memory, a key concept in the script, is memory allocated at runtime rather than at compile time. This allows for more flexibility in managing memory as the size and lifespan of memory allocation can be determined during the execution of a program. The video explains how dynamic memory is used in C and C++, highlighting its importance for managing large data structures whose size may not be known until the program is running.

💡Stack

The stack is a segment of memory that stores local variables and information related to function calls. It operates on a last-in, first-out principle, where the most recent function call's data is the first to be removed when the function returns. The script uses the stack to illustrate how memory is allocated for local variables during function execution, and how this allocation is managed automatically by the system.

💡Heap

The heap is another segment of memory used for dynamic memory allocation. Unlike the stack, the heap does not have a fixed size and can grow or shrink during the lifetime of an application. The video script explains the heap as a large pool of memory from which programmers can allocate and free memory as needed, emphasizing the need for careful management to avoid memory leaks.

💡Global Variables

Global variables are variables that are defined outside of any function and are accessible throughout the entire program. They are stored in a separate segment of memory and maintain their value throughout the program's execution. The script mentions global variables in the context of memory allocation and the importance of using them judiciously to avoid unnecessary memory consumption.

💡Malloc

Malloc is a function in C used to allocate a specified amount of memory on the heap. The script explains how malloc is used to request memory for storing data, such as integers or arrays, and how it returns a pointer to the allocated memory. Proper use of malloc is crucial for dynamic memory management in C programs.

💡Free

Free is a function in C that deallocates memory previously allocated by malloc. The script emphasizes the importance of calling free to release memory that is no longer needed, preventing memory leaks and ensuring efficient use of memory resources.

💡New Operator

In C++, the new operator is used for dynamic memory allocation, similar to malloc in C. The script contrasts the use of new with malloc, highlighting that new is type-safe and does not require typecasting, making it more convenient and safer for allocating memory in C++ programs.

💡Delete Operator

The delete operator in C++ is used to deallocate memory that was previously allocated with the new operator. The script explains that just as new is used for allocation, delete is used to free up memory, ensuring that dynamically allocated memory is properly managed in C++ programs.

💡Stack Overflow

Stack overflow occurs when the call stack exceeds the memory reserved for it, typically due to excessive function calls or recursion without an exit condition. The script warns about the potential for stack overflow, illustrating the limitations of the stack and the importance of managing function calls and recursion carefully.

💡Memory Management

Memory management is the process of allocating, using, and freeing memory in a computer program. The script discusses various aspects of memory management, including the allocation of memory on the stack and heap, the use of malloc and free in C, and new and delete in C++. Proper memory management is essential for writing efficient and stable programs.

Highlights

Memory is a crucial resource for any machine, and understanding its architecture is essential for programmers.

The memory in a typical architecture is divided into four segments: instruction, static/global variables, function calls and local variables, and heap.

Static or global variables have a lifetime equal to the application and are accessible throughout its lifecycle.

Local variables are declared inside functions and only exist during the function's execution time.

The stack frame is the memory allocated on the stack for a method's execution, including local variables and return information.

The size of the stack frame is calculated at compile time, and it cannot grow during runtime.

Heap memory, unlike stack, can vary in size during the application's lifetime and is not subject to fixed allocation rules.

Heap is also known as the free pool of memory or free store, and it can grow as long as system memory permits.

Dynamic memory allocation on the heap is controlled by the programmer and requires careful management to avoid memory wastage.

The term 'heap' in memory management does not refer to the heap data structure commonly studied in computer science courses.

In C, dynamic memory allocation is handled by the functions malloc, calloc, realloc, and free.

C++ offers new and delete operators for dynamic memory allocation, providing type safety and eliminating the need for typecasting.

When malloc cannot allocate memory, it returns null, which is important for error handling in programming.

The scope of variables allocated on the heap does not automatically deallocate when the function completes, unlike on the stack.

Global variables should only be used when needed across multiple functions and throughout the entire program lifecycle to avoid unnecessary memory usage.

Stack overflow can occur if the call stack grows beyond the reserved memory, such as in the case of infinite recursion.

Declaring large data types like arrays as local variables on the stack requires knowing the size at compile time, which can be limiting.

The heap provides a flexible solution for scenarios where the size of data structures needs to be determined at runtime.

Transcripts

play00:00

Memory, is one important and crucial resource on our machine and it is

play00:08

always good to know the architecture of memory, the way operating

play00:12

system manages memory and the way memory is accesible to us as

play00:17

programmers.

play00:18

In this lesson we will discuss the concept of dynamic

play00:21

memory and we will see how to work with dynamic memory using C or

play00:25

C++.

play00:27

The memory that is assigned to a program or application in a

play00:32

typical architecture can be divided into four segments.

play00:37

One segment of

play00:38

the memory is assigned to store the instructions that need to be

play00:44

executed.

play00:46

Another section stores all the static or global variables, the

play00:51

variables that are not declared inside a function, and that have the

play00:54

whole lifetime of an application, they are accesible anywhere during the

play00:58

whole life cycle of the application as long as the application is running.

play01:03

One section of the memory is used to store all the information of

play01:08

function calls and all the local variables and we have also talked about

play01:12

stack in our lesson on Call by Reference.

play01:16

Local variables are declared

play01:18

inside a function and they live only till the time the function is executing.

play01:24

The amount of memory set aside for these three segements: the text

play01:28

segment, the global variable segment and the stack, does not grow

play01:31

while the application is running.

play01:32

We will come back to why we use this

play01:35

fourth segment- heap , in a while.

play01:38

Let us first understand how these

play01:40

three segments of the memory are used when a program executes.

play01:44

I

play01:45

have a simple C program here.

play01:47

We have a function square that gives me

play01:49

the square of a number.

play01:51

We have another function Square of Sum that is

play01:54

given two arguments x and y, and it returns us the square of x plus y.

play01:59

And, in the main method, I am just calling this function Square of Sum

play02:04

passing it two arguments a and b.

play02:07

Let us now see what happens in the

play02:09

memory when this program executes.

play02:12

Let us say this rectangle in green

play02:15

here is memoryreserved as stack and the rectangle in orange is the

play02:20

memory reserved as Static or Global variable section.

play02:24

When the program

play02:25

starts executing, first the main method is invoked.

play02:27

When the main

play02:28

method is invoked, some amount of memory from the stack is allocated

play02:33

for execution of main.

play02:35

And this total is a global variable, so it should sit

play02:38

in the global section.

play02:40

The amount of memory allocated in stack for

play02:42

execution of main can also be called the stack frame for the method

play02:47

main.

play02:48

All the local varibales, arguments, and the information where this

play02:53

function should return back to, all this information is stored within this

play02:58

stack frame.

play02:59

The size of the stack frame for a method is calculated

play03:02

when the program is compiling.

play03:04

Now, when main calls Square of Sum

play03:07

method, let's write shortcut SOS, for Square of Sum, then a stack frame

play03:14

is allocated for the call to Square Of Sum, all these local varibales x, y

play03:20

and z will sit in this particular stack frame.

play03:22

Now, Sum of Square calls

play03:24

Square,lets again put a shortcut here for square, so another stack frame

play03:29

for square and it will have its own local variables.

play03:32

At any time during the

play03:34

execution of the program, the function at the top of the stack is

play03:38

executing and rest are kind of paused, waiting for the function above to

play03:44

return something and then it will resume execution.

play03:48

I have drawn these

play03:49

play and pause button here, in case you do not understand.Ok, so this

play03:53

total is a global variable , it's here in this section.

play03:58

Global variable

play03:59

because it is not declared inside a function.

play04:02

We can access it anywhere,

play04:03

and then we go to this particular statement where we call Square of

play04:06

Sum, and Square of Sum is calling Square and so this is called our call

play04:11

stack.

play04:12

This program may not be the best way to implement this logic.

play04:15

I

play04:16

have written this program this way so that I can have some nested

play04:19

methods calling each other.

play04:21

Let's say right now we are at this particular

play04:23

statement, we are executing this statement.

play04:26

So, at this stage the call

play04:28

stack will have these three methods.

play04:30

Now, when this method finishes,

play04:32

we will return back to this particular statement.

play04:35

As soon as Square

play04:36

function will return, it will be cleared from the stack memory and now

play04:41

Square of Sum function will resume.

play04:44

Once again when Square of Sum

play04:46

finished, the control will come to this particular line total is equal to

play04:50

Square of Sum and main will resume again.

play04:54

Now, main will call printf, so

play04:58

once again printf will go to the top of the stack.

play05:02

Printf will finish and the

play05:04

control will come back again to main and now main will finish.

play05:07

And, now

play05:08

main finishes, program will also finish.So, In the end, our global variables

play05:13

will also get cleared.

play05:15

There was no need in this program to keep this

play05:17

variable total as global.

play05:19

We should assign a variable as global only if it

play05:23

is needed at multiple places in multiple functions and it is needed for

play05:27

the whole lifetime of the program, otherwise it is a waste of memory to

play05:33

keep a variable for the whole lifetime of program execution.

play05:37

We had kept

play05:38

one global variable in this program just to understand the concepts.

play05:42

Here, I must point out one more thing, when our program starts, our

play05:49

operating system allocates some amount of reserved space, let's say OS

play05:54

allocates 1 MB of space as stack, but the actual allocation of the stack

play05:59

frame and the actual allocation of the local variables happens from the

play06:04

stack during runtime and if our call stack grows beyond the reserved

play06:09

memory for the stack like for example, if a method A calls B, B calls C

play06:14

and we go on calling and we exhaust the whole space reserved for the

play06:19

stack, then this is called stack overflow and in this case our program will

play06:26

crash.

play06:27

One common case of stack overflow is when you write a bad

play06:31

recursion and your program goes infinitely into recursion.

play06:36

So, as we can

play06:37

see, there are some limitaions of stack.

play06:39

The memory set aside for stack

play06:42

does not grow during runtime.

play06:44

Application cannot request more memory

play06:46

for stack.

play06:47

So, if it is 1 MB, then if the allocation of variable and functions

play06:52

in stack exceeds 1 MB, our program will crash.

play06:55

Further the allocation and

play06:57

deallocation of memory onto the stack happens by a set rule.

play07:01

When a

play07:02

function is called, it is pushed onto the stack, when it finishes, it is

play07:07

popped out of the stack or removed from the stack.

play07:09

It is not possible to

play07:10

manipulate the scope of a variable if it is on the stack.

play07:15

Another

play07:16

limitation is that if we need to declare a large data type, like an array as

play07:20

local variable, then we need to know the size of the array at compile

play07:25

time only.

play07:26

If we have a scenario like we have to decide how large the

play07:29

array will be based on some parameter during runtime then it is a

play07:34

problem with stack.

play07:36

For all these problems, like allocaing large chunks of

play07:39

memory or keeping variable in the memory till the time we want, we

play07:44

have heap.

play07:47

Unlike stack, application's heap is not fixed.

play07:52

It's size can vary

play07:53

during the lifetime of the application and there is no set rule for

play07:57

allocation or deallocation of the memory.

play08:00

A programmer can totally

play08:01

control how much memory to use from the heap, till what time to keep

play08:07

the data in the memory during the applications lifetime and heap can

play08:12

grow as long as you do not run out of memory on the system itself.

play08:17

That

play08:18

is a dangerous thing also and we need to be really careful about using

play08:21

heap for this reason.

play08:23

We also sometimes call heap, free pool of memory

play08:27

or free store of memory.

play08:29

We can get as much as we want from the heap.

play08:32

How heap is implemented by the operating system, language runtime or

play08:38

the compiler, is something which can vary, which is a thing of computer

play08:42

architecture.

play08:43

But an abstracted way of looking at the heap as a

play08:47

programmer is that this is one large free pool of memory available to us

play08:52

that we can use flexibly as per our need.

play08:57

Heap is also called dynamic

play08:59

memory and using the heap is referred to as dynamic memory allocation.

play09:05

Let us now see how to use the heap in out C or C++ program.

play09:10

I will clear

play09:11

this code in the left and I will draw one more rectangular block here for

play09:17

heap.

play09:18

there is one more thing that I must point out before moving

play09:21

forward.

play09:22

Heap is also one data structure and if you do not know about

play09:26

this data structure Heap yet, you will learn about it in your Data

play09:30

Structure course.

play09:31

But this nomenclature here has nothing to do with

play09:34

heap data structure.

play09:36

The term heap is being used only for the large free

play09:40

pool of memory.

play09:42

Heap data strcutre does not come anywhere in this

play09:44

context.

play09:45

This term often confuses a lot of people when they know about

play09:49

heap data structure.

play09:50

Stack is also one data strcutre but the stack

play09:53

segment of the memory is actually an implementation of the stack data

play09:56

structure but heap is not an implementation of the heap data structure.

play10:00

To use dynamic memory in C, we need to know about four functions

play10:06

malloc, calloc, realloc and free.

play10:12

To use dynamic memory in C++, we need

play10:14

to know about two operators new and delete.

play10:20

These four functions can

play10:22

also be used in C++, as C++ has backward compatibility.

play10:28

It is only a

play10:29

superset of C. But C++ programmers use mostly these two operators,

play10:34

new and delete.

play10:35

We will see some code examples and try to understand

play10:40

how things happen when dynamic memory is used.

play10:43

Let us first pick up

play10:44

some code examples in C. Let us write a C program.

play10:48

I will clean up some

play10:50

of the stuff in the right.

play10:51

1 MB for stack, this was just an assumption.

play10:53

In

play10:54

reality, the size of the stack will be decided by the operating system and

play10:57

the compiler.

play10:59

It is a thing of computer architecture.

play11:01

Coming back to the

play11:02

code, if we declare a variable like this, then this variable is a local

play11:05

variable.

play11:06

It goes on the stack.

play11:08

Memory for this particular variable a' will

play11:10

be allocated from the stack frame of the main method.

play11:16

Let us say we

play11:17

want to store an integer on the heap.

play11:19

To reserve, or get some space

play11:21

allocated on the heap, we need to call the malloc function, something

play11:25

like this.

play11:26

The malloc function asks for how much memory to allocate on

play11:29

the heap in bytes.

play11:31

When we say malloc and pass as argument size of

play11:35

integer, then we are saying that "Hey, give me a block of memory, which

play11:39

is 4 bytes. 4 bytes is the typical size of the integer.

play11:43

So, one block of 4

play11:44

bytes will be reserved or allocated on the heap and malloc will return a

play11:49

pointer to starting address of this block.

play11:52

And, malloc returns a void

play11:53

pointer.

play11:54

Let us say, the starting address of this block of 4 bytes is 200,

play11:58

then malloc will return us address 200.

play12:01

Now, we have a pointer to

play12:03

integer p, which is a local variable to main.

play12:06

So, this will be allocated in

play12:09

the stack frame of the main method.

play12:11

We have done a typecasting here,

play12:12

because malloc returns pointer to void, sorry, void pointer and p is an

play12:17

integer pointer.

play12:18

Now, p stores the address of this block of memory which

play12:22

is 200.

play12:23

So, we have got some block of memory on the heap which we

play12:27

want to use to strore an integer.

play12:30

Right now, we do not know what's there

play12:32

in this particular block of memory.

play12:35

If we want to fill in something here,

play12:37

we need to dereference this location using the pointer p and then put in

play12:41

some value.

play12:42

In fact the only way to use memory on heap is through

play12:47

reference.

play12:48

All the malloc function does it, looks for some free space in

play12:51

the heap, books it or reserves it for you and give back the pointer.

play12:55

And

play12:56

the only way you can access this particular block by keeping a pointer

play12:58

variable which will be local to your function.

play13:02

Now, let us write something

play13:04

like this.

play13:05

After writing 10 in this particular block, i will go ahead and

play13:10

make one more call to malloc.

play13:12

When I make one more call to malloc, one

play13:15

more block of 4 bytes is allocated on the heap and let us say the address

play13:19

is 400 for this block.

play13:21

Now, the address that is returned by the second

play13:24

call to malloc, we store this address in the variable p.

play13:27

So, what happens

play13:28

is, that p is now pointing to the address 400.

play13:32

The next line writes

play13:33

address 20 to this address.

play13:36

We allocated one more block and we

play13:38

modified the address in p to point to this block.

play13:41

The previous block will

play13:43

still sit in the heap.

play13:44

This memory we are still consuming, it will not be

play13:47

cleared off automatically.

play13:49

At any point in our program , if we are done

play13:51

using some block of memory which is dynamically allocated using

play13:56

malloc, we also need to clear it, because it is unnecessary consumption

play14:00

of memory which is an important resource.

play14:02

So, what we should have

play14:03

done here is that once we were done using this particular block of

play14:08

memory at 200, we should have made a call to the function free.

play14:13

Any

play14:14

memory which is allocated using malloc, is cleared off by calling free.

play14:18

And to free, we pass the pointer to the starting address of the memory

play14:21

block.

play14:22

So, now with this code this first block of memory will first be

play14:25

cleared and then we will be pointing to anohter memory address.

play14:30

It is

play14:31

the responsibility of the programmer to clear anything on the heap if he

play14:34

has allocated it and does not need it any further.

play14:38

So, you see, in terms of

play14:39

the scope of the variable, anything allocated on the heap is not

play14:43

automatically deallocated when the function completes like on the stack.

play14:47

And, it does not need to live for the whole lifetime of the application

play14:52

like a global variable.

play14:53

We can control when to free anything on the heap,

play14:57

when to deallocate anything on the heap.

play14:59

If we wanted to store an array

play15:01

in the heap, like let's say we wanted to store an integer array into the

play15:04

heap, then all we do is make a call to the malloc asking for one block of

play15:09

memory equal to the total size of the array in bytes.

play15:12

So, if we want an

play15:13

integer array of 20 elements, then we will make a call to malloc asking

play15:20

20 X size of int which will be 4 number of bytes.

play15:24

So, what will happen

play15:25

now, is that one bit of contigous block of byte for 20 integers will be

play15:31

allocated on the heap and we will get the starting address of the heap.

play15:34

So, we kind of get the base address of the array.

play15:39

This p will point here, to

play15:41

the base address of this block.

play15:43

And then in our code we can use this, 20

play15:46

integers as P[0], P[1], P[2] and so on.

play15:51

As we know, P[0] is same as

play15:53

saying value at address P, and P[1] is same as saying value at address

play15:58

P+1.

play15:59

This is what it means.

play16:02

One more thing, if malloc is not able to find

play16:04

any free block of memory, is not able to allocate some memory on the

play16:08

heap, it returns null.

play16:10

So, for error handling, we need to know this and we

play16:13

need to write our code appropriately.Malloc and Free.

play16:18

The use of malloc

play16:19

and free is C style code.

play16:21

If we want to write the same code, same logic

play16:24

in C++, there is not much difference.

play16:27

Instead of using these two

play16:28

functions, malloc and free, we will use two operators: New and

play16:33

Delete.And, we will write our code something like this.

play16:35

So, instead of

play16:36

malloc, we are using the New operator here and instead of using free,

play16:41

we are using delete here.

play16:43

If we want to allocate an array, we use

play16:46

something like this where we put the size in brackets here.

play16:50

And, if we

play16:51

want to free an array, we use this particular operator delete and two

play16:54

brackets, sorry, one bracket.

play16:57

With C++, we do not have to do all these

play17:00

typecastings, like malloc returns void and we need to typecast it back to

play17:03

integer pointer.

play17:04

New and Delete operators are type safe.

play17:07

What it means

play17:08

is, that they are used with a type and return pointers to a particular type

play17:12

only.

play17:13

So, here p will get a pointer to integer only.

play17:15

We will be talking

play17:17

about dynamic memory allocation and other library function in more

play17:21

detail in the coming lessons.

play17:22

So, Thanks for watching!

Rate This

5.0 / 5 (0 votes)

Related Tags
Memory ManagementC ProgrammingC++ TutorialDynamic AllocationHeap MemoryStack OverflowMalloc FunctionFree FunctionNew OperatorDelete OperatorProgramming Concepts