13-MemoryPointers.pptx

  1. 1、本文档共24页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
13-MemoryPointers

Programming Abstractions Cynthia Lee CS106X Topics: Last week, with Marty Stepp: Making your own class Arrays in C++ This week: Memory and Pointers Revisit some topics from last week Deeper look at what a pointer is Hexadecimal! Dynamic Memory allocation Linked nodes Linked List data structure (if we have time) Binary tree data structure 2 Arrays (revisit from last week) Arrays (11.3) type* name = new type[length]; A dynamically allocated array. The variable that refers to the array is a pointer. The memory allocated for the array must be manually released, or else the program will have a memory leak. (_) Another array creation syntax that we will not use*: type name[length]; A fixed array; initialized at declaration; can never be resized. Stored in a different place in memory; the first syntax uses the stack and the second uses the heap. (discussed later) * For 106X, I would like you to know this syntax and be able to diagram what it does, but Marty Stepp was right in that we won’t generally be using it in code you write (for style/design reasons). Arrays on the stack and heap void myfunction() { int x = 5; int y; int arr[2]; arr[1] = 3; int *heapArr = new int[2]; // bad -- memory leak coming! } What happens when myfunction() returns? Memory main() x: y: 0x0 myfunction() arr: heapArr: ArrayList (revisit from last week) Freeing array memory delete[] name; Releases the memory associated with the given array Must be done for all arrays created with new Or else the program has a memory leak. (No garbage collector like Java) Leaked memory will be released when the program exits, but for long-running programs, memory leaks are bad and will eventually exhaust your RAM int* a = new int[3]; a[0] = 42; a[1] = -5; a[2] = 17; ... delete[] a; Destructor (12.3) // ClassName.h // ClassName.cpp ~ClassName(); ClassName::~ClassName() { ... destructor: Called when the object is deleted

文档评论(0)

l215322 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档