/*
 * CS107 lecture example: valgrind and memory errors
 *
 * This program demonstrates possible memory-related issues that can arise
 * from either copying in too much data using strcpy, or asking for the
 * length of a character array without a null-terminating character.
 */

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

void example1(char *str) {
    printf("--- strcpy the passed-in string (could be any length) into buffer of length 6 --- \n\n");
    
    char string1[6];
    strcpy(string1, "Hello");
    char string2[6];
    strcpy(string2, "Hello");
    
    strcpy(string1, str);
    printf("string1 = %s\n", string1);
    printf("string2 = %s\n", string2);
    printf("\n");
}

void example2(char *input) {
    printf("--- copy in first 3 chars of passed-in string (maybe without null terminator), call strlen\n\n");

    char string[10];
    strncpy(string, input, 3);
    
    int length = strlen(string);
    printf("strlen = %d\n\n", length); 
}

int main(int argc, char *argv[]) {
    // e.g. ./valgrind_examples 1 mystr
    if (argc == 3) {
        if (strcmp(argv[1], "1") == 0) {
            example1(argv[2]);
        } else if (strcmp(argv[1], "2") == 0) {
            example2(argv[2]);
        }
    } else if (argc == 2) {
        // e.g. ./valgrind_examples mystr
        example1(argv[1]);
        example2(argv[1]);
    }

    printf("Done.\n");
    return 0;
}
