Skip to content

Instantly share code, notes, and snippets.

@zedshaw
Created January 4, 2015 17:18
Show Gist options
  • Save zedshaw/c20a69f17578909523c4 to your computer and use it in GitHub Desktop.
Save zedshaw/c20a69f17578909523c4 to your computer and use it in GitHub Desktop.
A simple version of copying via string lengths then breaking it on purpose
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define MAXLINE 10 // in the book this is 1000
void safercopy(size_t to_length, char to[], size_t from_length, char from[])
{
int i = 0;
// if you're butthurt I put this if-statement here you can remove it to show me how to
// break the for-loop and make it run forever
if(to != NULL && from != NULL && (int)to_length > 0 && (int)from_length > 0) {
for(i = 0; i < to_length && i < from_length && from[i] != '\0'; i++) {
to[i] = from[i];
}
} else {
// normally you'd then have an error here, but I'm keeping the function call
// the same as in the book for the challenge
}
}
int main(int argc, char *argv[])
{
int i = 0;
// use heap memory as many modern systems do
char *line = malloc(MAXLINE);
char *longest = malloc(MAXLINE);
assert(line != NULL && longest != NULL && "memory error");
// initialize it but make a classic "off by one" error
for(i = 0; i < MAXLINE; i++) {
line[i] = 'a';
}
// check for various defects
safercopy(MAXLINE, longest, MAXLINE, line);
// BUGS ON PURPOSE: lie about sizes to cause overflows, but still for-loop exits
// main way to break it
safercopy(MAXLINE+1000, longest, MAXLINE+1000, line);
// lie about size
safercopy(MAXLINE+1000, longest, MAXLINE-10000, line);
// really lie about size with invalid size_t variable
safercopy((size_t)-1, longest, (size_t)-1, line);
// pass in null pointers
safercopy((size_t)-1, NULL, (size_t)-1, line);
safercopy((size_t)-1, longest, (size_t)-1, NULL);
safercopy((size_t)-1, NULL, (size_t)-1, NULL);
free(line);
free(longest);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment