Tom Kelliher, CS 320
Jan. 31, 2003
Project 0 handout.
Exercise, structures, pointers.
Discussion of Chapter 1.
malloc()
--- memory allocation.
void *malloc(size_t size);
free()
--- memory de-allocation.
void free(void *ptr)
#include <stdlib.h>
.
int
array:
void createAndDestroy(int size) { int *data; int i; data = (int *) malloc(size * sizeof(int)); if (data == NULL) return; for (i = 0; i < size; i++) data[i] = 0; free((void *) data); }
typedef struct qnode { struct qnode *next; struct qnode *prev; int key; /* Additional or alternate fields here. */ } qnode; qnode* head, temp, insert, delete; /* Don't forget to check malloc's return value! */ head = (qnode*) malloc(sizeof(qnode)); head->next = head->prev = NULL; head->key = 5; temp = (qnode*) malloc(sizeof(qnode)); temp->key = 99; head->next = head->prev = temp; temp->next = temp->prev = head temp = (qnode*) malloc(sizeof(qnode)); temp->key = 73; insert = head; /* New item inserted AFTER item pointed to by insert. */ temp->next = insert->next; temp->prev = insert; insert->next->prev = temp; insert->next = temp; delete = head->prev; /* The following is incorrect, from a memory allocation point-of-view. * Why? How can it be fixed? */ free((void*) delete); delete->prev->next = delete->next; delete->next->prev = delete->prev;