-1

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:

1
  • You're returning the address of a local array. That array goes out of scope the moment the function returns. After that, it may not be validly accessed. Do you understand that local variables only exist while the function invocation that creates them is active? Commented Mar 19, 2023 at 2:59

1 Answer 1

1

Undefined Behavior

char *lowercase3(const char* str) {
    char copy[strlen(str) + 1];
    return copy;
}

This returns a pointer to memory local to the function. This is undefined behavior.

Consider get a better compiler

I would also recommend using a better compiler, clang 16.0.0 would give this code the following warnings:

https://godbolt.org/z/jzdWYz36a

<source>:11:12: warning: address of stack memory associated with local variable 'copy' returned [-Wreturn-stack-address]
    return copy;
           ^~~~
1 warning generated.
Sign up to request clarification or add additional context in comments.

3 Comments

I have edited the question, please have a look. Thank you!
At no point in your code are you printing the pointer. You're printing %s, which dereferences the pointer, which is undefined behavior.
You are also printing 5 strings. It sounds like there is one in particular you are concerned is printing the string null. Perhaps you could include the explicit output your application gives to make it explicit which value you are confused about.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.