I am trying to replicate a problem with returning stack variable in C but it didn't work as I expected. This is the issue I want to reproduce function returning address of stack variable. And here is the result of calling the function on stack, heap, and constant
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char *lowercase3(const char* str) {
char copy[strlen(str) + 1];
for (int i = 0; i <= strlen(str); i++) {
copy[i] = tolower(str[i]);
}
return copy;
}
int main() {
char stack[13] = "Le Land";
char heap[13] = "Standford";
char const* const_literal = "Hello World!";
char* result1 = lowercase3(stack);
char* result2 = lowercase3(heap);
char* result3 = lowercase3(const_literal);
// print stack heap and const_literal
printf("stack: \"%s\", result: \"%s\"\n", stack, result1);
printf("heap: %s, result: %s\n", heap, result2);
printf("const_literal: %s, result: %s\n", const_literal, result3);
}
However it just returns null when returning copy.
I ran the debugger and the variable "copy" is an char array with value leland. So I expect it to return the address of the stack variable "copy". Why does the function return null here? Edit: