-1

I have to return a char * from a routine which has a char[]
This should be simple but sometimes str1 results in garbage

char* foo (int ch) {

char str[10];
char* str1;

if (foo1(str,ch)) {
str1 = str;
} else {
str1 ="???"
}
return(str1);
}

boolean foo1(char *s, int c) {
/*find s based on c*/
}

Edited by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

Votes + Comments
Not a snippet; no code tags.
3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Narue
0

OH,
"str1 = str;"it's a bug, str[10] is just local varible.the value of str[10] after you invoking funcion foo() is unmeaning.

1

>how can this be taken care of?
You have no choice but to allocate a new block of memory. Since str is a local array but needs a longer lifetime, you can replace it with dynamic memory:

char* foo (int ch) {
  char* str = malloc(10);

  if (!foo1(str, ch))
    strcpy(str, "???");

  return(str);
}

But that requires the calling code to call free as well (a step often forgotten). A usually better alternative is to pass the buffer in as a parameter. That way the calling code owns it and can decide how to manage the memory:

char* foo (char* str, int ch) {
  if (!foo1(str, ch))
    strcpy(str, "???");

  return(str);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.