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*/
}
Dave Sinkula commented: Not a snippet; no code tags. -2

Recommended Answers

All 3 Replies

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.

how can this be taken care of?

>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);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.