C++(真正)安全的标准字符串搜索?

标签 c++ string search standards

缓冲区溢出问题是众所周知的。因此,我们有幸使用标准库函数,例如 wcscat_s()。 Microsoft 的好心人已经创建了类似的安全字符串函数,例如 StringCbCat()。

但是我遇到了一个问题,我需要在一点内存中搜索一个字符串。标准库函数:

wcsstr( wchar_t* pMem, wchar_t* pStr ) 

看起来不错,但是... 有时我的内存包含垃圾,有时是字符串。当它是垃圾时,我有时会用完分配的内存页,[=访问冲突]。是的,我可以编写自己的函数。但我的问题是是否有任何“标准”函数可以进行安全的字符串搜索,例如:

"wcsstr_s( wchar_t* pMem, size_t uiSize, wchar_t* pStr )" ?

谢谢

[编辑] 感谢并感谢 Charles Bailey 对我的问题做出了完美的回答。也感谢其他人的努力。

对于那些怀疑我的情景是否正常的人:是的,当然,我的内存中永远不会有垃圾是件好事。但我可以想象几种可能发生这种情况的场景。在我的特殊情况下,它是逆向工程,我搜索的内存实际上不是“我的内存”,它属于另一个我无法控制的进程。

(另一种假设情况可能是需要跟踪损坏的内存的棘手调试情况。)

最佳答案

可能不是您正在寻找的答案,但这里最好的解决方案可能是正确初始化您的字符串和指针。如果你的内存包含垃圾,为什么不做一些体面的事情并设置

yourString[0] = '\0';

如果它真的只是一个任意的缓冲区,你最好使用像 memcmp 这样的东西并沿着 N 个字符滑动内存缓冲区的指针(其中 N 是您感兴趣的字符数减去您正在比较的字符串的长度)。这可能不是最有效的实现方式,但我认为应该是一种相当稳健的方法。

[编辑] 您的问题引起了我的兴趣,足以让我做一些小实验。鉴于您似乎正在寻找更多 C 风格的答案,这里是我想出的一小段代码来详细说明我的 memcmp 建议:

// SearchingMemoryForStrings.cpp : Defines the entry point for a win32 consol application
// Purpose : Demonstrates a way to search a section of memory for a particular string
//

#include <stdio.h>
#include <string.h>

#define VALUE_NOT_FOUND (-1)

int FindStringInBuffer( const char* pMemBuffer, const size_t& bufferSizeInBytes, const char* pStrToFind )
{
    int stringFound = VALUE_NOT_FOUND; // Return value which will be >= 0 if we find the string we're after
    const char* pMemToMatch = NULL; // An offset pointer to part of 'pMemBuffer' which we'll feed to memcmp to find 'pStrToFind'

    // Set up some constants we'll use while searching
    size_t lenOfStrToFind = strlen( pStrToFind );
    size_t lastSearchablePosition = bufferSizeInBytes - lenOfStrToFind;

    // Search the memory buffer, shifting one character at a time for 'pStrToFind'
    for( size_t i = 0; i <= lastSearchablePosition; i++ ) {
        pMemToMatch = &pMemBuffer[i];
        if( memcmp(pMemToMatch, pStrToFind, lenOfStrToFind) == 0 ) {
            // We found the string we're looking for
            stringFound = i;
            break;
        }
    }

    return stringFound;
}

void ReportResult( int returnVal, const char* stringToFind )
{
    if( returnVal == VALUE_NOT_FOUND ) {
        // Fail!
        printf("Error, failed to find '%s' - search function returned %d\n", stringToFind, returnVal );
    }
    else {
        // Win!
        printf("Success, found '%s' at index %d\n", stringToFind, returnVal );
    }
}

void FindAndReport( const char* pMemBuffer, const size_t& bufferSizeInBytes, const char* pStrToFind )
{
    int result = FindStringInBuffer( pMemBuffer, bufferSizeInBytes, pStrToFind );
    ReportResult( result, pStrToFind );
}

int main( int argc, char* argv[] )
{
    const int SIZE_OF_BUFFER = 1024; // Some aribitrary buffer size
    char some_memory[SIZE_OF_BUFFER]; // The buffer of randomly assigned memory to look for our string
    const char* stringToFind = "This test should pass";
    const char* stringYouWontFind = "This test should fail";

    FindAndReport( some_memory, SIZE_OF_BUFFER, stringYouWontFind ); // Should fail gracefully

    // Set the end of the buffer to the string we're looking for
    memcpy( &some_memory[SIZE_OF_BUFFER-strlen(stringToFind)], stringToFind, strlen(stringToFind) );

    FindAndReport( some_memory, SIZE_OF_BUFFER, stringToFind ); // Should succeed this time and report an index of 1003

    // Try adding at some arbitrary position
    memcpy( &some_memory[100], stringToFind, strlen(stringToFind) );

    FindAndReport( some_memory, SIZE_OF_BUFFER, stringToFind ); // Should still succeed but report the offset as 100

    FindAndReport( some_memory, SIZE_OF_BUFFER, stringYouWontFind ); // Should still fail


    return 0;
}

该片段在 Visual Studio 2008 下编译为 Win32 控制台应用程序。给我以下内容:

Error, failed to find 'This test should fail' - search function returned -1
Success, found 'This test should pass' at index 1003
Success, found 'This test should pass' at index 100
Error, failed to find 'This test should fail' - search function returned -1

FindStringInBuffer 函数是您想要的,如果您需要处理宽字符,则需要进行一些转换,但这至少应该给您一些想法可以继续。如果您确实想出了一个 wchar 版本,我很想看看解决方案是什么样的(我自己没有处理过)。

关于C++(真正)安全的标准字符串搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/916455/

相关文章:

c++ - 使用 FreeType 库创建文本位图以在 OpenGL 3.x 中绘制

c++ - 不同的派生类共享相同的方法

java - 字符串中字符的位置和重复

java - 确定 List<Foo> 的最简洁方法包含 Foo.getBar() = "Baz"的元素?

c++ - 如何从 C++ 中的 stringstream 变量中提取二进制数据?

c++ - 派生类依赖函数

.net - 将字符串转换为字节数组时,我如何知道使用什么编码方案?

c++ - C++中的字符串初始化有什么区别?

algorithm - Sphinx 怎么能这么快地进行排序?

php - 在php中将多个表结果合并到一张表中