[c] Returning a C string from a function

I am trying to return a C string from a function, but it's not working. Here is my code.

char myFunction()
{
    return "My String";
}

In main I am calling it like this:

int main()
{
  printf("%s", myFunction());
}

I have also tried some other ways for myFunction, but they are not working. For example:

char myFunction()
{
  char array[] = "my string";
  return array;
}

Note: I am not allowed to use pointers!

Little background on this problem:

There is function which is finding out which month it is. For example, if it's 1 then it returns January, etc.

So when it's going to print, it's doing it like this: printf("Month: %s",calculateMonth(month));. Now the problem is how to return that string from the calculateMonth function.

This question is related to c

The answer is


If you really can't use pointers, do something like this:

char get_string_char(int index)
{
    static char array[] = "my string";
    return array[index];
}

int main()
{
    for (int i = 0; i < 9; ++i)
        printf("%c", get_string_char(i));
    printf("\n");
    return 0;
}

The magic number 9 is awful, and this is not an example of good programming. But you get the point. Note that pointers and arrays are the same thing (kind of), so this is a bit cheating.


You can create the array in the caller, which is the main function, and pass the array to the callee which is your myFunction(). Thus myFunction can fill the string into the array. However, you need to declare myFunction() as

char* myFunction(char * buf, int buf_len){
  strncpy(buf, "my string", buf_len);
  return buf;
}

And in main function, myFunction should be called in this way:

char array[51];
memset(array, 0, 51); /* All bytes are set to '\0' */
printf("%s", myFunction(array, 50)); /* The buf_len argument  is 50, not 51. This is to make sure the string in buf is always null-terminated (array[50] is always '\0') */

However, a pointer is still used.


Or how about this one:

void print_month(int month)
{
    switch (month)
    {
        case 0:
            printf("January");
            break;
        case 1:
            printf("february");
            break;
        ...etc...
    }
}

And call that with the month you compute somewhere else.


Return string from function

#include <stdio.h>

const char* greet() {
  return "Hello";
}

int main(void) {
  printf("%s", greet());
}

Your function prototype states your function will return a char. Thus, you can't return a string in your function.


Your function return type is a single character (char). You should return a pointer to the first element of the character array. If you can't use pointers, then you are screwed. :(


A char is only a single one-byte character. It can't store the string of characters, nor is it a pointer (which you apparently cannot have). Therefore you cannot solve your problem without using pointers (which char[] is syntactic sugar for).


Your problem is with the return type of the function - it must be:

char *myFunction()

...and then your original formulation will work.

Note that you cannot have C strings without pointers being involved, somewhere along the line.

Also: Turn up your compiler warnings. It should have warned you about that return line converting a char * to char without an explicit cast.


A C string is defined as a pointer to an array of characters.

If you cannot have pointers, by definition you cannot have strings.


Note this new function:

const char* myFunction()
{
    static char array[] = "my string";
    return array;
}

I defined "array" as static. Otherwise when the function ends, the variable (and the pointer you are returning) gets out of scope. Since that memory is allocated on the stack, and it will get corrupted. The downside of this implementation is that the code is not reentrant and not threadsafe.

Another alternative would be to use malloc to allocate the string in the heap, and then free on the correct locations of your code. This code will be reentrant and threadsafe.

As noted in the comment, this is a very bad practice, since an attacker can then inject code to your application (he/she needs to open the code using GDB, then make a breakpoint and modify the value of a returned variable to overflow and fun just gets started).

It is much more recommended to let the caller handle about memory allocations. See this new example:

char* myFunction(char* output_str, size_t max_len)
{
   const char *str = "my string";
   size_t l = strlen(str);
   if (l+1 > max_len) {
      return NULL;
   }
   strcpy(str, str, l);
   return input;
}

Note that the only content which can be modified is the one that the user. Another side effect - this code is now threadsafe, at least from the library point of view. The programmer calling this method should verify that the memory section used is threadsafe.


Based on your newly-added backstory with the question, why not just return an integer from 1 to 12 for the month, and let the main() function use a switch statement or if-else ladder to decide what to print? It's certainly not the best way to go - char* would be - but in the context of a class like this I imagine it's probably the most elegant.


char* myFunction()
{
    return "My String";
}

In C, string literals are arrays with the static constant memory class, so returning a pointer to this array is safe. More details are in Stack Overflow question "Life-time" of a string literal in C


Well, in your code you are trying to return a String (in C which is nothing but a null-terminated array of characters), but the return type of your function is char which is causing all the trouble for you. Instead you should write it this way:

const char* myFunction()
{

    return "My String";

}

And it's always good to qualify your type with const while assigning literals in C to pointers as literals in C aren't modifiable.