Function returning pointer into static string

96 views Asked by At

I have this program, that prints Lala. Although i do not understand why i do not get a compilation error in the main function when i call foo(). I suspect it has something to do with the fact that str is static char*, but i do not get it.foo() returns a pointer to a character. So its call shouln't look like this: char* result = foo(); Here is the program:

#include <stdio.h>

char *foo() {
    static char * str = "LalaLalaLalaLala";
    str+=4;
    return str;
}
int main() {
    foo();
    foo();
    printf("%s\n", foo());
    return 0;
}

Can someone explain this to me? Thank you in advance.

3

There are 3 answers

0
dbush On BEST ANSWER

Just because a function returns a value doesn't mean you have to use it. It's perfectly valid (though not necessarily wise depending on the context) to not capture or otherwise use the return value of a function. The printf function returns an int value but it's almost never used.

So the line foo(); is valid code.

0
Vlad from Moscow On

It is entirely unimportant that the pointer str declared in the function foo has static storage duration.

What is important is that the string literal "LalaLalaLalaLala" pointed to by the pointer str has static storage duration. So a returned pointer from the function is valid until it will point outside the string literal that has type char[17] due to the pointer arithmetic within the function

str+=4;

Pay attention to that in C string literals have static storage duration. And initially in this declaration

static char * str = "LalaLalaLalaLala";

the pointer str is initialized by the address of the first character of the string literal before the function will get the control and then in each call of the function it is incremented.

0
gulpr On
char *foo() {
    static char * str = "LalaLalaLalaLala";
    char *str1 = something;
  1. str has a static storage duration and it is (1) initialized only once, (2) keeps its value between the function calls and (3)identifier str is visible only in the function scope
  2. str1 has automatic storage duration and it (1) is initialized every time you call the function foo, (2) does not keep* its value between the function calls and (3)identifier str is visible only in the function scope

Your code is correct and it compiles correctly as you do not have to use function return value.

You can force gcc (and probably other compiler too) to warn you if you do not use the return value by using attributes or compile options.

[[nodiscard]] char *foo() {
   /* .... */
<source>:9:5: warning: ignoring return value of 'foo', declared with attribute 'nodiscard' [-Wunused-result]
    9 |     foo();
      |     ^~~~~