开发者

valid char array (is this a valid string)

I am filling a char array using ReadProcessMemory and I am curious to know what is the 'correct/standard/best' way to determine if the returned char array contains a valid string. I'm not worried about the string, it can contain the a-zA-Z0-9 plus spaces and characters such as './_' and a few other things but really all I want to know if it is val开发者_开发知识库id and just not full of junk.

int char_read_length = 255;
char data[255];
memset(data, 0, char_read_length);
ReadProcessMemory( hProcess, (void *)start, data, char_read_length, &lpRead);

Thanks.


It can be treated as a string if it contains a NUL character to terminate the string. If there is no NUL, treating it as a string will run off the end of the buffer and cause very bad things to happen. Thus:

bool is_it_a_string = memchr(data, 0, char_read_length);


Couple of things here:

  1. We do not know what you mean by "valid". If you want a string that contains only those characters, write yourself a loop that checks each character to see if it is one of those characters.
  2. There's no need to call memset on your array, because ReadProcessMemory is going to write to that buffer for you anyway.
  3. Where is lpRead defined? If it really is a lp variable (which stands for "long pointer"), you should not be taking it's address before passing it to ReadProcessMemory. If it is not a pointer then you should change it's name so that it doesn't start with LP. (Actually, you might want to not use Hungarian notation anyway but if you're going to use it at least do it correctly)
  4. If this is C++, you should be using static_cast rather than the C style cast to cast the character pointer to a void pointer.


I'd probably just use something like the following (note that using this would require ensuring that data is properly '\0' terminated):

char const validChars[] = "abcdefghijklmnopqrstuvwxyz"
                          "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                          "0123456789"
                          "./_"
                          " ";  // add whatever other characters are considered valid


bool isValidString(char const* s) 
{
    return strspn(s, validChars) == strlen(s);
}

If you want to check that the entire 255 bytes is 'valid', then you'd need to check that strlen(data) == 255, too.

There's probably a nice C++ STL algorithm that can handle this just as well, but I'd probably still just use strspn() due to a certain form of laziness.

Note that you probably need to check for an error return from ReadProcessMemory().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜