CS 241: System Programming Fall 2008 C No Evil Homework Due start of class, Friday, September 5, 2008 Each of these examples can appear inside C programs. The ... means additional (irrelevant) instructions. For each example, answer the following questions: (a) What does the code attempt to do? (b) Why does it not work correctly? (c) How can the code be corrected? 1. int x, *ip; float y, *fp; ... ip = &x; fp = (float *)ip; y = *fp; 2. int x,*p; *p=x; 3. int **array = (int **) malloc(n*sizeof(int)); 4. int x; scanf("%f",&x); 5. void increment(int x) { x++; } ... for(x=0;x<10;increment(x)) { printf("x=%d\n",x); } 6. char str[5]; strncpy("abcde",str,5); printf("%s", str); 7. int *p; p = 0; *p = 12; 8. void test(char*s1, char*s2) { return strcmp(s1,s2) == 0; } 9. int *p; int *q; p = q; *p = 30; 10. char *s; s=(char *) malloc (100); s="hello"; free(s); 11. char somespace[8]; strcat(somepace,"12345678"); 12. int *array; int i,n; ... for(i=0;i 5) return(1); } 21. int i; ... while(i>0); printf("i=%d\n",i--); 22. char *get_result () { char result[80]; sprintf(result, "here is the result."); return(result); } int main() { char *p; p = f(); printf("f() returns: %s\n", p); } 23. char s[50]; scanf("%50s",s); s[50] = '\0'; 24. int i,x[10]; for(i=0;i<=10;i++) x[i]=i*2; 25. int *array; int i,j; for(i=0;i<5;i++) { array = malloc(5*sizeof(int)); for(j=0;j<5;j++) array[j] = i*j; } 26. int* x,y; ... printf("%d\n",*y); 27. char *str,*p; ... p=str; while(*p!=0) { *p++; p++; } 28. int a, b; char buf[100]; scanf("%d %d", &a, &b); sprintf(buf, "result: %d %d"); 29. int getval(char* mystring) { char *p, *malloc(); p = malloc(25); scanf("%s", p); mystring = p; free(p); } 30. #define cube(x) x*x*x #define double(x) x+x x = 3; y = cube(x + 1); z = 5 * double(x); 31. char *str; int x; ... switch(str) { case "one": x=1; break; case "two": x=2; break; case "three: x=3; break; default: x=0; } 32. int i; ... switch(i) { case 1: printf("One.\n"); case 2: printf("Two.\n"); case 3: printf("Three.\n"); default:printf("Something Else.\n"); } 33. char c = "a"; 34. #define mytan(x) sin(x)/cos(x) x = 3; y = myfunction(x++); 35. if (x < 0) { printf("Invalid value.\n"); exit; }