Q:

C++. How can I free memory correctly?

Written code to find and remove the largest word in a string without the using of library functions. Everything works fine. But when I want to free memory, the result is negative (displays an empty line). If you remove the call to the memory release function, everything will work correctly, but there will be a leak of memory.
How do I fix it? Please help me.
#include <iostream>

using namespace std;

int length(char *text) // string length
{
    char *begin = text;
    while(*text++);

    return text - begin - 1;
}

int size(char **text) // size of two-dimensional array
{
    int i = 0;
    while(text[i]) i++;

    return i;
}

void free_memory(char **text)
{
    for(int i=0; i<size(text); i++)
        delete text[i];

    delete [] text;
}

char **split(char *text, char delim)
{
    int words = 1;
    int len = length(text);

    for(int i=0; i<len; i++)
        if(text[i] == delim) words++;

    char **result = new char*[words + 1];
    int j = 0, t = 0;

    for(int i=0; i<words; i++)
    {
        result[i] = new char[len];

        while(text[j] != delim && text[j] != '\0') result[i][t++] = text[j++];

        j++;
        t = 0;
    }

    result[words + 1] = nullptr;

    return result;
}

char *strcat(char *source, char *destination)
{
    char *begin = destination;

    while(*destination) destination++;
    *destination++ = ' ';
    while(*source) *destination++ = *source++;

    return begin;
}

char *removeWord(char *in_string)
{
    char **words = split(in_string, ' ');
    int max = length(words[0]);
    int j = 0;

    for(int i=0; i<size(words); i++)
        if(max < length(words[i]))
        {
            max = length(words[i]);
            j = i;
        }

    int index;
    char *result;

    if(!j) index = 1;
    else index = 0;

    result = words[index];

    for(int i=0; i<size(words); i++)
        if(i != j && i != index)
            result = strcat(words[i], result);

    free_memory(words); // I want free memory here

    return result;
}

int main()
{
    char text[] = "audi and volkswagen are the best car";

    cout << removeWord(text) << endl;

    return 0;
}

A:

You have two issues. First is that result is assigned to a memory location in words. Second, is that you're storing the result of strcat in words[i] which will likely not have enough room (see strcat documentation).
result = new char[len(in_string)+1]; // +1 for space for null char

// the old loop reversed the word order -- if you want to keep doing
// that, make this a descending loop
for(int i=0; i<size(words); i++)
    if(i != j && i != index)
        strcat(result, words[i]);

free_memory(words);

return result;

So that when you free words, what result points to is also free'd. You would then need to free your result in main().
int main()
{
    char text[] = "audi and volkswagen are the best car";
    char * result = removeWord(text);
    cout << result << endl;

    delete[] result;

    return 0;
}

