Below is the pig latin example from today, fixed so that it works! The bugfix is noted in the code below. However, how could you update this code to avoid a stack buffer overflow?
pig.c
#include <stdio.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
// read input
// pig latinify
// - find a vowel
// - reorder and ayify
// write it out
const char *findVowel(const char *word) {
const char *s = strpbrk(word, "aeiouAEIOU");
// Avoid returning NULL from strpbrk if no
// vowel was in the word.
if (s != NULL)
return s;
return word;
}
void showPig(const char *word) {
const char *vowel = findVowel(word);
printf("%s", vowel); // print the "ig"
fwrite(word, sizeof(char), vowel - word, stdout); // print the "p"
printf("ay"); // print ay
}
int main (int argc, const char *argv[]) {
// Stack buffer overflow possibility here!
// We should be VERY CAREFUL and fix this!
char buffer[4096];
int index = 0;
// BUGFIX: In class, we were always reading into
// the first position in the array. The post-class
// bug fix was to update the position into the
// buffer that the next character should be read.
// read(0, buffer, 1) --> read(0, &buffer[index], 1)
while(read(0, &buffer[index], 1)) {
if(isalpha(buffer[index])) {
index++; // If letter, collect the word in buffer
} else {
// If not a letter, handle the prior word
char saveme = buffer[index];
if (index > 0) {
buffer[index] = '\0';
showPig(buffer);
}
// Write the non-letter out
fwrite(&saveme, sizeof(char), 1, stdout);
// Reset the buffer
index = 0;
}
}
return 0;
}