

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Solutions to various programming exercises from a system programming course, including questions related to pointers, memory allocation, and string manipulation. For each example, the document answers the questions: (a) what does the code attempt to do? (b) why does it not work correctly? (c) how can the code be corrected?
Typology: Assignments
1 / 3
This page cannot be seen from the preview
Don't miss anything!


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?
int x, *ip; float y, *fp;
ip = &x; fp = (float *)ip; y = *fp;
int x,*p; *p=x;
int **array = (int *) malloc(nsizeof(int));
int x; scanf("%f",&x);
void increment(int x) { x++; } ... for(x=0;x<10;increment(x)) { printf("x=%d\n",x); }
char str[5]; strncpy("abcde",str,5); printf(โ%sโ, str);
int *p; p = 0; *p = 12;
void test(chars1, chars2) { return strcmp(s1,s2) == 0; }
int *p; int *q; p = q; *p = 30;
char *s; s=(char *) malloc (100); s="hello"; free(s);
char somespace[8]; strcat(somepace,"12345678");
int array; int i,n; ... for(i=0;i<n;i++) array[i] = ii;
char s1[5] = "word"; char s2[5] = "word"; if (s1 == s2) printf("The strings are equal.\n");
int a; if (0 < a < 5) printf("a is greater than 0 but less than 5.\n");
int a,b; if (a =! b) printf("a and b are not the same.\n");
int *array; int i,j,10; array = malloc(10sizeof(int )); for(i=0;i<10;i++) for(j=0;j<10;j++) array[i][j] = ij;
int x=5; if (x=1) printf("one.\n"); else print("not one.\n");
int x,y; char s[50]; scanf("%d %d %5s",x, y, s);
int main(int argc, char *argv[]) { printf(argv[1]); }
int main (a) { if (a > 5) return(1); }
int i; ... while(i>0); printf("i=%d\n",i--);
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); }
char s[50]; scanf("%50s",s); s[50] = '\0';
int i,x[10]; for(i=0;i<=10;i++) x[i]=i*2;
int array; int i,j; for(i=0;i<5;i++) { array = malloc(5sizeof(int)); for(j=0;j<5;j++) array[j] = i*j; }
int* x,y; ... printf("%d\n",*y);
char str,p; ... p=str; while(*p!=0) { *p++; p++; }
int a, b; char buf[100]; scanf("%d %d", &a, &b); sprintf(buf, "result: %d %d");
int getval(char* mystring) { char *p, *malloc(); p = malloc(25); scanf(โ%sโ, p); mystring = p; free(p); }
#define cube(x) xxx #define double(x) x+x x = 3; y = cube(x + 1); z = 5 * double(x);