# teaching machines

## CS 330 Lecture 14 – Postfix Calculator and Make

February 22, 2013 by . Filed under cs330, lectures, spring 2013.

### Agenda

• what ?s
• program this!
• making stack reusable
• managing compilation with make

### Program This

Write a function strappend, which

• takes two strings as parameters
• makes the first bigger so that it can hold both strings
• copies the second string onto the end of the first
• returns nothing

### Code

#### strappend.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void strappend(char **base, const char *suffix) {
int total_chars = strlen(*base) + strlen(suffix) + 1;
char *bigger = (char *) malloc(total_chars * sizeof(char));

strcpy(bigger, *base);
strcat(bigger, suffix);
printf("bigger: %s\n", bigger);

free(*base);
*base = bigger;
printf("base: %s\n", *base);

// Suffix is not necessarily on heap. It's not ours to reclaim.
/* free(suffix); */

// DON'T DO THIS, PAL! We're relying on you.
/* free(bigger); */
}

int main(int argc, char **argv) {

char *foo = strdup("Angry Beyonce");
strappend(&foo, " a ring");
printf("foo: %s\n", foo);

free(foo);

return 0;
}

#### stack.c

#define EZMALLOC(type, n) \
(type *) malloc((n) * sizeof(type))

stack_t *make_stack(int capacity) {
stack_t *stack = EZMALLOC(stack_t, 1);
stack->size = 0;
stack->capacity = capacity;
stack->items = EZMALLOC(int, stack->capacity);
}

void stack_push(stack_t *stack, int item) {
if (stack->size >= stack->capacity) {
fprintf(stderr, "Stack full, you foo bag.\n");
exit(1);
}

stack->items[stack->size] = item;
++stack->size;
}

int stack_pop(stack_t *stack) {
if (stack->size == 0) {
fprintf(stderr, "Stack empty, you foo bag.\n");
exit(1);
}

int item = stack->items[stack->size - 1];
--stack->size;
return item;
}

#### stack.h

#ifndef STACK_H
#define STACK_H

struct stack_t {
int size;
int capacity;
int *items;
};

typedef struct stack_t stack_t;

stack_t *make_stack(int capacity);
void stack_push(stack_t *stack, int item);
int stack_pop(stack_t *stack);

#endif

#### stack_user.c

#include <stdio.h>
#include <stdlib.h>

#include "stack.h"

int main(int argc, char **argv) {

stack_t *stack = make_stack(10);

stack_push(stack, 42);
printf("stack_pop(stack): %d\n", stack_pop(stack));

return 0;
}

### Haiku

Languages have warts
Some of us are monsters — “Blarp!”
That’s Monster for “Like”

1. Di says:

Hi Chris,

In strappend, why do we use strdup for foo? why not char *foo = “jsdhaisudh”; instead?

1. Chris Johnson says:

Either way would be fine. Given that the call to strappend will have foo point to something on the heap, it’s more consistent to make to make that string initially on the heap as well.

1. Chris Johnson says:

Of course, we should describe in the documentation what happens to the old memory. If we say we’re going to free it, it better have been malloc’d beforehand.