FOR C PROGRAMMING LANGUAGE
Which of the three C programming language functions are likely to cause problems in a program that calls them? For those causing problems, briefly explain why.
int* f1(void) {
int y = 10;
return (&y);
}
int* f2(void) {
int* ptr; *ptr = 10; return ptr;
}
int* f3(void) {
int *ptr;
ptr = (int *) malloc (sizeof(int)); *ptr = 10;
return ptr;
}
f1: [explanation goes here]
f2: [explanation goes here]
f3: [explanation goes here]
Program f1 and f2 are going to cause problem in a program that call them.
int* f1(void) {
int y = 10;
return (&y);
}
This function returns the address of a local variable 'y'. Here the variable’s is only valid inside the function and it's lifetime ends after the function returns, then if we use in the return value, it will produces undefined behavior.
int* f2(void) {
int* ptr; *ptr = 10;
return ptr;
}
This Function also produces undefined behavior because it dereferences and returns an uninitialized pointer. In other words, It has not been assigned to point to anything, and its initial value is indeterminate.
int* f3(void) {
int *ptr;
ptr = (int *) malloc (sizeof(int)); *ptr = 10;
return ptr;
}
This Function has no errors but we need to take care that return
value is not NULL before using it, and call free
when
the memory is no longer needed.
Get Answers For Free
Most questions answered within 1 hours.