Home:ALL Converter>Do I need to malloc C-style strings?

Do I need to malloc C-style strings?

Ask Time:2020-08-04T16:42:29         Author:

Json Formatter

I recently started using Arduino so I still have to adapt and find the differences between C/C++ and the Arduino language.

So I have a question for you.

When I see someone using a C-style string in Arduino (char *str), they always initialize it like this (and never free it) :

char *str = "Hello World";

In pure C, I would have done something like this:

int my_strlen(char const *str)
{
    int i = 0;

    while (str[i]) {
        i++;
    }
    return (i);
}

char *my_strcpy(char *dest, char const *src)
{
    char *it = dest;

    while (*src != 0) {
        *it = *src;
        it++;
        src++;
    }
    return (dest);
}

char *my_strdup(char const *s)
{
    char *result = NULL;
    int length = my_strlen(s);

    result = my_malloc(sizeof(char const) * (length + 1));
    if (result == NULL) {
        return (NULL);
    }
    my_strcpy(result, s);
    return (result);
}

and then initialize it like this:

char *str = my_strdup("Hello World");
my_free(str);

So here is my question, on C-style Arduino strings, is malloc optional or these people just got it wrong?

Thank you for your answers.

Author:,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/63243168/do-i-need-to-malloc-c-style-strings
yy