0

Possible Duplicate:
Returning a string from a function in C

So I'm trying to combine element 0 of an array of cstring of a and b and return the pointer to the caller. Inside the function returnStr is set but when I assign the return from the calling function the value is now not what it should be.

char* combineCstr(char **a, char **b)
{
    char *returnStr;
    char str[20];
    strcpy(str, a[0]);
    strcat(str, "+");
    strcat(str, b[0]);

    returnStr= str;
    return returnStr;
}

I'm thoroughly confused and any help would be appreciated, thanks.

Community
  • 1
  • 1
user1795609
  • 147
  • 1
  • 2
  • 7
  • you have to make `str` array `static` – Davide Berra Feb 05 '13 at 14:13
  • 2
    @DavideBerra That is really a questionable suggestion, in general. It would make the function super-scary to use. – unwind Feb 05 '13 at 14:14
  • 1
    @DavideBerra - if you make it static, whatever one combineCstr returns will be overwritten by new invocations of combineCstr. You need to use malloc or similar. Static is *not* a good idea. – tucuxi Feb 05 '13 at 14:14
  • There are so many questions like this. This results from a fundamental misunderstanding of memory management in C – Charles Salvia Feb 05 '13 at 14:14
  • You're right guys. I think a need a vacation ;) – Davide Berra Feb 05 '13 at 14:20
  • The _sane_ way to do this is `void combineCstr (char returnStr[20], const char* a, const char* b);`, where returnStr, a and b are pointers. It doesn't make _any_ sense to use pointer to pointer in this case. – Lundin Feb 05 '13 at 14:52
  • @Lundin: Why not return something, like an `int`? Also, `char returnStr[20]` in that context is just a confusing way of saying `char *returnStr`. – netcoder Feb 05 '13 at 15:05
  • @netcoder Why return int if there is no int to return? returnStr[20] is a way of saying "put an allocated buffer of 20 chars here, or the program will crash". I don't know how holy the number 20 is here, but I doubt that a professional C programmer will find this notation confusion. – Lundin Feb 05 '13 at 16:10

1 Answers1

4

You are returning a local array (str). When your function exits, that memory is reclaimed, so this is not valid code. You should have received compiler warnings for this.

If you cannot trust that either input has space for the result, you must allocate new memory using e.g. malloc() and concatenate the strings into that memory. It will not be affected by your function exiting.

tucuxi
  • 17,561
  • 2
  • 43
  • 74
unwind
  • 391,730
  • 64
  • 469
  • 606