Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic memory allocation in C and C++

Similar presentations


Presentation on theme: "Dynamic memory allocation in C and C++"— Presentation transcript:

1 Dynamic memory allocation in C and C++
程式設計 潘仁義 CCU COMM

2 Pointers void main () { int num = 3; int *nump = # …..

3 Dynamic memory allocation in C (1/3)
void some_function () { int *nump; char *letp; planet_t *planetp; …

4 Dynamic memory allocation in C (2/3)
void some_function () { int *nump; char *letp; planet_t *planetp; … #include <stdlib.h> nump=(int*) malloc(sizeof(int)); letp = (char*) malloc(sizeof(char)); planetp = (planet_t *) malloc(sizeof(planet_t));

5 Dynamic memory allocation in C (3/3)
void some_function () { int *nump; char *letp; planet_t *planetp; … nump=(int*) malloc(sizeof(int)); letp = (char*) malloc(sizeof(char)); planetp = (planet_t *) malloc(sizeof(planet_t)); *nump = 307; *letp = ‘Q’; *planetp = blank_planet;

6 Allocation of Arrays with calloc

7 Allocation of Arrays with calloc (cont’d)

8 Returning cells to the Heap
… free(letp); free(nump); free(planetp); … free(string1); free(array_of_nums); free(array_of_planets); double *xp, *xcopyp; xp =(double *)malloc(sizeof(double)); *xp = 49.5; xcopyp = xp; free(xp); 『*xcopyp』should not be used after it freed or errors can result

9 Dynamic memory allocation in C++
int *nump; char *letp; planet_t *planetp; char *string1; int *array_of_nums; planet_t *array_of_planets; nump= new int; letp = new char; planetp = new planet_t; string1 = new char[str_size]; array_of_nums = new int[num_nums]; array_of_planets = new planet_t[num_planets]; delete nump; delete letp; delete planetp; delete [ ] string1; delete [ ] array_of_nums; delete [ ] array_of_planets;

10 Linked list Children’s Pop Beads in a Chain

11 Linked list Structures with pointer components
typedef struct node_s { char current[3]; int volts; struct node_s *linkp; } node_t; node_t *n1_p, *n2_p, *n3_p; n1_p = (node_t *)malloc(sizeof(node_t)); n1_p->volts = 115; n2_p = (node_t *)malloc(sizeof(node_t)); n2_p->volts = 12; n3_p = n2_p; /* 令n3_p指向n2_p所指的地方 */

12 可用 n2_p->volts n3_p->volts 或 n1_p->linkp->volts
Linking Two Nodes n1_p->linkp = n2_p; /* 令上面的linkp 指向下面 */ 可用 n2_p->volts n3_p->volts 或 n1_p->linkp->volts

13 Three-Node Linked List
n2_p->linkp = (node_t *) malloc(sizeof(node_t)); n2_p->linkp->volts=220; strcpy(n2_p->linkp->current, “AC”); n2_p->linkp->linkp = NULL;

14 Linked list operations
After an Insertion After a Deletion

15 Common programming error
var->component is valid only if var is of a pointer-to-structure The most common error is an attempt to follow a NULL pointer Checking before access Do not attempt to reference a node after freeing it


Download ppt "Dynamic memory allocation in C and C++"

Similar presentations


Ads by Google