Dynamic Memory, The Heap, Memory Leaks, Recursive Composition

Dynamic Memory Allocation: malloc

allocated memory at runtime

 

Stack vs Heap:

Stack Frames store per function call:

Local variables, parameters, return value

       Heap stores:

Dynamic allocations... at runtime

 

Must be explicitly de-allocated using free after the program no longer needs the memory.

Otherwise a memory leak will occur If the program loses track of an allocation, it is unable to be deallocated

 

Two functions and a special operator allow us to use the memory of the heap:

The type size_t is simply a typedef for an unsigned integer

size_t is used to count bytes

 

Often, we use the sizeof operator to help calculate the number of bytes required by the dynamic allocation

 

 

Using malloc

 

malloc requires passing in the number of bytes that will be used by program.

This can be done by using the sizeof to get the number of bytes for a variable or structure to be stored

 

malloc will returns an address (a pointer) of the first element in the block of memory... or null (zero) if the allocation is not possible

 

 

Allocate a block of 5 ints:

Store the pointer to the first element in the array once it has been allocated.

Then treat the block of memory like the array that it is

 

When allocate 2D blocks of memory:

Just calculate the number of bytes required... and ask malloc for the allocation

 

 

Remember! At runtime an array is just a pointer:

print the same %p value for both block_of_data and p_first

 

Remember we can treat dynamically allocated memory as an array if we want:

 

malloc () gives us the memory until we give it back with free ():

 

If we forget to deallocate, we create a memory leak!

This will make our program crash eventually, or at least diminish our computer's capabilities temporarily

 

 

Exercise:

Requirement (9x05c - Memory Sharing)

 

Implementation

 

 

 

Requirement (9x06c - Bad Array Passing)

 

Implementation

This program is designed for printing the star-time according to the assignnments.

Errors Encountered

 

Debug

Because in the program has used start_time three times!

Test

 

Requirement (9x07d - C-String Analyser)

Implementation

Test

 

Requirements (9x08a)& Design

Implementation

 

Test

 

Requirements (9x08c - num_spaces)

Implementation

 

Test

Error occurred

 

Debug

Program will never enter this loop.

 

Lesson Learn

Distinguish the index or array[index].

Requirement (10x08a - Recursive Movie)

Implementation

 

Test

 

 

10x10a - ASCII Card

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值