Skip to content

[text] String returned from TextToLower gets changed unexpectedly throughout the program #1292

Closed
@filipencopav

Description

@filipencopav
#include <stdio.h>
#include <raylib.h>

int main(void)
{
	const char *lol;
	lol = TextToLower("HELLO_WORLD!");
	printf("%s\n", lol); /* prints hello_world */
	TextToLower("BROTHERS");
	printf("%s\n", lol); /* prints "brothers" */
	/*
	 * Where did i modify `lol`? Nowhere! In fact, it is even constant.
	 * Then what happened?
	 */
	return 0;
}

It's because TextToLower returns a pointer to a statically allocated buffer.

const char *TextToLower(const char *text)
{
    static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };

    for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++)
    {
        if (text[i] != '\0')
        {
            buffer[i] = (char)tolower((unsigned char)text[i]);
        }
        else { buffer[i] = '\0'; break; }
    }

    return buffer;
}

This issue can also arise at any point in any other function that returns a pointer to a static variable.

Solution: Make TextToLower take in input and output parameters.

void TextToLower(char *dst, const char *src, size_t dst_len)
{
    for (int i = 0; i < dst_len; i++)
    {
        if (src[i] != '\0')
        {
            dst[i] = (unsigned char)tolower(src[i]);
        } else break;
    }
    dst[dst_len] = '\0';
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions