Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
filipencopav opened this issue Jun 29, 2020 · 1 comment

Comments

@filipencopav
Copy link

filipencopav commented Jun 29, 2020

#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';
}
@filipencopav filipencopav reopened this Jun 29, 2020
@filipencopav filipencopav changed the title [text] const char * gets changed throughout the app unexpectedly. [text] String returned from TextToLower gets changed unexpectedly throughout the program Jun 29, 2020
@raysan5
Copy link
Owner

raysan5 commented Jun 29, 2020

@Theamazingwaffle Sorry, raylib text functions are designed to work that way. The reason, they are intended to be combined with DrawText() calls.

@raysan5 raysan5 closed this as completed Jun 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants