#include #include // strcpy example int s1(void) { char ha[30]; strcpy(ha, "Now is the the time"); printf("%s\n%d\n", ha, strlen(ha)); } // strcpy and strcar int s2(void) { char ha[50]; strcpy(ha, "Now is the time"); strcat(ha, " for all good men"); printf("%s\n", ha); } /******* *** stack smashing detected ***: terminated Aborted (core dumped) *******/ int s3(void) { char ha[15]; strcpy(ha, "Now is the"); strcat(ha, " time for all good men to come"); printf("%s\n", ha); } //strlen example int s4(char str[]) { printf("Length: %d\n", strlen(str)); } // my implementation of strlen, with a bounded string length // will return -1 if get to bound before null terminator int s5(const char * str, int maxlen) { int len=0; for (len=0; len<2048; len++) { if (*(str++)=='\0') { printf("Length: %d\n", len); return len; break; } } return -1; } // no null terminator int s6() { char aa[2048]; for (int i=0;i<26;i++) { aa[i]='A'+i; } printf("length: %d\n", strlen(aa)); for (int i=21; i<30; i++) { printf("%2d |%c| %d\n", i, aa[i], aa[i]); } } // My strcpy. Assumes that target has the space int s7(char * target, const char * source) { for (int i=0; source[i]!=0; i++) { target[i]=source[i]; } } // my strcpy with pointers char * s8(char * target, const char * source) { char * tar = target; while (*tar++ =*source++); return target; } // compare to s3 int s9() { char tgt[100]; sprintf(tgt, "%s %s", "now is the time", "for all good men"); printf("%s\n", tgt); return 0; } //Usage: a.out NUM // where NUM indicates the sample you want to run // NUM shouuld be in 1-8 inclusive int main(int argc, char * argv[]) { switch (argv[1][0]) { case '1': s1(); break; case '2': s2(); break; case '3': s3(); break; case '4': s4("Now is the time"); break; case '5': s5("for all good men to come to the aid"); break; case '6': s6(); break; case '7': { char tar[2048]; s7(tar, "Now is the time for all good men to come to the aid of their party"); printf("Copied: %s\n", tar); } break; case '8': { char tar[2048]; s8(tar, "Now is the time for all good men to come to the aid of their party"); printf("Copied: %s\n", tar); } break; default: printf("SWITCH:What to do with %s\n", argv[1][0]); break; } }