{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

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 *) malloc(strlen(currentpl)+1); strcpy(word, currentpl); printf(“%s\n”, word); currentpl = endword+1; free((void *) word); } word = (char *) malloc(strlen(currentpl)+1); strcpy(word, currentpl); printf(“%s\n”, word); free((void *) word); return 0; } malloc() Example Memory is initialized to zero Takes two parameters – Number of items
Background image of page 1

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

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

{[ snackBarMessage ]}