I have a char-array and I want to remove whitespace just before or after or both, the word (or phrase) and not in the middle.
For example:
"hello" --> "hello"
" hello" --> "hello"
" hello " --> "hello"
" " --> ""
This is my code:
#include <stdlib.h>
#include <string.h>
int main(void) 
{
    char s[] = " prova ";
    char *t = NULL;
    if (s == NULL)
    {
        t = NULL;
    }
    else {
        int n = strlen(s);
        t = malloc(sizeof(char)* (n + 1));
        for (int i = 0; i <= n; ++i)
        {
            t[i] = s[i];
        }
        int k = 0;
        if (s[0] == ' ')
        {
            ++k;
            t = realloc(t, sizeof(char)*n);
            for (int i = 0; i <= n - 1; ++i)
            {
                t[i] = s[i + 1];
            }
        }
        if (s[n - 1] == ' ')
        {
            if (k == 1)
            {
                int j = 0;
                t = realloc(t, sizeof(char)*(n - 1));
                for (int i = 0; i <= n - 2; ++i)
                {
                    t[i] = t[i];
                    j = i;
                }
                t[j] = 0;
            }
            else
            {
                int j = 0;
                t = realloc(t, sizeof(char)*n);
                for (int i = 0; i <= n - 1; ++i)
                {
                    t[i] = t[i];
                    j = i;
                }
                t[j] = 0;
            }
        }
    }
    return t;
}
The debugging does not give me error or other things, but I know there is a problem with memory and heap and I don't know how to remove it.
I looked for other questions similar to mine on this platform and they exist, but none of the answers solved my problem.
Please give me some advice, thank you
 
     
     
     
    