ProgrammingHardWipro · Cognizant pattern
What happens when this runs?
What happens when this runs?
int *makeArray(void) {
int local[10];
for (int i = 0; i < 10; i++) local[i] = i;
return local;
}
int main(void) {
int *arr = makeArray();
printf("%d", arr[3]);
}- A. 3, guaranteed by the standard
- B. Undefined behaviour: local is a stack array whose storage is reclaimed the instant makeArray() returns; arr dangles
- C. Compile-time error: cannot return a local array
- D. 0, since arrays are always zero when dangling
Correct answer: B. Undefined behaviour: local is a stack array whose storage is reclaimed the instant makeArray() returns; arr dangles
Unlike heap memory from malloc, local (an automatic array) has its storage reclaimed as soon as makeArray() returns — the compiler would actually warn about returning the address of a local variable here. Dereferencing arr afterward is undefined behaviour; it may appear to 'still work' by luck since nothing has overwritten that stack memory yet, but this is never guaranteed.
More C Programming questions
- What happens when this runs? c int arr[5] = {1, 2, 3, 4, 5}; int p = arr; int val = p[-1]; printf("%d", val);
- What happens when this runs? c int global; int main(void) { printf("%d", global); }
- What happens when this runs? c void fillBuffer(char buf, int size) { for (int i = 0; i <= size; i++) { buf[i] = 'A'; } } int main(void) {…
- What happens when this runs? c int a = 5; int b = a++ + a++ + a++; printf("%d %d", a, b);
- What happens when this runs? c struct Point { int x, y; }; struct Point p = malloc(sizeof(struct Point)); printf("%d", p->x);
- What happens when this runs? c char concat(const char a, const char b) { char result[100]; strcpy(result, a); strcat(result, b); return…