C By Discovery (4th Edition)

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Intermediate Programming CSE 1320 Lecture 14 Chapter 11:11.5-11.6 • stdlib.h – ptr = (type *) malloc(size_t bytes) • In: Number of bytes to allocate • Out: Address of first byte in newly allocated buffer char *string, buffer[50]; string = (char *) malloc(strlen(buffer)+1); – free() • In: Pointer to space to be freed (void *) free((void *) string) Dynamic Allocation and De- allocation of Memory #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 512 int main(void) { char instring[BUFFER_SIZE], *currentpl, *endword, *word; printf(“Enter a line of text:\n”); fgets(instring, BUFFER_SIZE, stdin); instring[strlen(instring)-1] = ‘\0’; currentpl = instring; while ((endword = strchr(currentpl, ‘ ‘)) != NULL) { *endword = ‘\0’; word = (char *) mal oc(strlen(cur entpl)+1); strcpy(word, currentpl); printf(“%s\n”, word); currentpl = endword+1; free((void *) word); } word = (char *) mal oc(strlen(cur entpl)+1); strcpy(word, currentpl); printf(“%s\n”, word); free((void *) word); return 0; } malloc() Example • Memory is initialized to zero • Takes two parameters
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/06/2011 for the course CSE 1320 taught by Professor Sprintston during the Spring '08 term at UT Arlington.

Page1 / 4

Lecture14 - Dynamic Allocation and Deallocation of Memory...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online