0

I'm trying to make a function which deletes l elements, starting from the k position. My function returns another set of chars after deleting the chars. String_length is a function which returns the length of the string.

Remove Chars

char * remove_chars(char s1[], int k, int l)
{
    int j = 0;
    if(string_length(s1) + 1 < k || string_length(s1) + 1 < l)
        return 0;
    else
    {
        char s2[100];
        for(int i = 0; s1[i] != '\0'; ++i)
        {
            if((i <= k - 1) || (i > k + l - 1 ))
            {

                s2[j] = s1[i];
                ++j;
            }
        }
        s2[j] = '\0';
        return s2;
    }
}

The problem is, that after I call the remove_chars function in main, it returns as null, but when I try to print s2 inside remove_chars function, it prints it out just like it was supposed to be.

Adrian Covaci
  • 67
  • 2
  • 12
  • Please see [Function returning address of local variable error in C](https://stackoverflow.com/questions/22288871/function-returning-address-of-local-variable-error-in-c). After the function returns, `s2` is dead, although there might be a ghost. – Weather Vane Nov 05 '18 at 21:17
  • `s2` is in the stack frame of `remove_chars`. So, after `remove_chars` returns, `s2` is no longer valid. The quick and dirty solution is to do: `static char s2[100]`. Or, have caller pass down `s2` as a separate arg (e.g. `char * remove_chars(char s2[100], char s1[], int k, int l)`. Or, copy back `s2` into `s1` before returning – Craig Estey Nov 05 '18 at 21:20

1 Answers1

0

You're returning the address of a local variable.

s2 is an array defined locally. When you then return s2, the array decays to a pointer to the first element. Once the function returns, s2 goes out of scope and the memory it used is no longer valid. Using a pointer to a variable that has gone out of scope unvokes undefined behavior.

Dynamically allocate memory instead so it will still be valid when the function returns.

char *s2 = malloc(strlen(s1)+1);

Don't forget to free the memory in the calling function when you're done using it.

dbush
  • 205,898
  • 23
  • 218
  • 273