Вопрос

I am doing some static analysis work on some old C++ code and my C++ is not the strongest. I have this piece of code:

void NIDP_clDPLogger::log(TCHAR *logString)
{
    TCHAR temp_logString[1024] = {0};
    _tcsncpy(temp_logString,logString,1024);
    temp_logString[1023] = NULL;
            ...

The static analysis tool is complaining here of indexing logString (the parameter passed in to function) at 1024 when it may be shorter (the size varies, 1024 is the max. size I guess). So I guess my fix is to check the size of logString and use that, like this:

void NIDP_clDPLogger::log(TCHAR *logString)
{

    size_t tempSize = sizeof(logString);
    TCHAR temp_logString[tempSize] = {0};
    _tcsncpy(temp_logString,logString,tempSize);
    temp_logString[tempSize-1] = NULL;

I am just wondering, will this work OK? Can anybody see any flaws/problems? Building and testing this project is slightly difficult so I am basically just looking for a sanity check before I go through all that. Or is there a better way for me to do it? Can I pass a size_t value in to _tcsncpy, because a hardcoded int was there before?

Thanks for all help.

Это было полезно?

Решение

sizeof(logString) will return the size of a TCHAR*, not the size of the array passed as arrays decay to pointers when passed as argument.

If it is guaranteed that logString is null terminated you could obtain its length using _tcslen(). Otherwise, the only way to know the size of logString is to pass it into the function as another argument.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top