0

I have to create a function that returns a string of characters from this one.

In parameter of the function there is (string, start index, len)

When I compile:

warning: address of stack memory associated with local variable 'ptr_s' returned [-Wreturn-stack-address]

I know that I have to allocate memory but I have restrictions I have to do it without.

I share my code with you:

char                *new_str(char const *s, unsigned int start, size_t len)
{
    char            new[len];
    size_t          i;

    i = 0;
    if (!s || len <= 0 || start >= strlen(s))
        return ("");
    while (i < len)
    {
        new[i] = s[start];
        i++;
        start++;
    }
    new[i] = '\0';
    return (new);
}

int main(void)
{
    char const a[] = "bonjour les amis, ca va ?";
    printf("%s", new_str(a, 0, 7));
    return (0);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sayari
  • 21
  • 3
  • Ok, well then, pass an 'out' array into the function as anotber argument. – Martin James Feb 19 '21 at 06:19
  • 1
    If there are restrictions on what you can use, you should state them in the question. It is not fair to those who would answer if you get an answer and then say "but I'm not allowed to use that". – Jonathan Leffler Feb 19 '21 at 06:58
  • It's surprising that one argument is of type `unsigned int` and another of `size_t`. It would be more sensible if both arguments were the same type — arguably `size_t` is a better choice. – Jonathan Leffler Feb 19 '21 at 07:02

1 Answers1

0

It means that you are return an address of stack memory from the function. This means that after you return the address of from the function, area of memory that you have returned from the function will be deallocated, therefore no longer usable.

The solution to this is to return a address of heap memory, this can be done by using malloc or similar dynamic memory allocation functions. Dynamic memory can pose a number of other issues to be considered, but that is another issue.

  • It's not entirely another issue. If the function returns dynamically allocated memory, it shouldn't be used directly as an argument to `printf()` as in the main program in the question. You have to save the returned value in a variable too so that the memory can be freed properly. Well, assuming that you need to avoid memory leaks. When the program exits on the next line, that isn't a pressing concern, but in most C programming, ensuring you don't leak memory is an important part of getting the code right. – Jonathan Leffler Feb 19 '21 at 07:01