views:

145

answers:

2

I'm trying to read a process memory using the following code:

void readdata(HANDLE phandle, LPCVOID paddress, SIZE_T datasize)
{
    char *buff;
    SIZE_T dataread;
    BOOL b = FALSE;

    buff = (char *) malloc (datasize);

    b = ReadProcessMemory(phandle, paddress, (LPVOID)buff, datasize, &dataread); 
    if(!b)
    {
     printf("error reading memory, err = %d\n", GetLastError());
     return;
    }

    printf("Data Read             = %d\n", dataread);
    printf("Len of actual buffer  = %d\n", strlen(buff));
    printf("Data = %s\n", buff);

    free(buff);
    return;
}

Now, phandle and paddress are known becuase I used WriteProcessMemory. I have the values from there. datasize is also known.

The function works ok, except for the following. ReadProcessMemory() returns dataread = 41 (which is correct, I passed 41 to datasize) but the actual length of the buff is 49. when I print buff i get my string + some garbage.

What am I doing wrong?

code is appreciated.

Thanks!

+1  A: 

Do you know that the data you read is a string? Ie. that it's null terminated? If not then using strlen() is guaranteed to be unreliable.

djna
yes, it is a string. I put it there (including the NULL char at the end)
wonderer
you put **strlen() + 1** bytes? Then, sorry guv, no idea.
djna
+1  A: 

The '\0' at the end of your string is likely not being copied, either out of your buffer when you write, or into your buffer when you read. As a result, printf() is just going to print from the beginning of your string until it sees a '\0', which may be after a number of garbage characters.

Jonathan
OK, how would I fix this (if this is the case)?I am writing the string there myself. the string is (for testing):"<1234567890> <hello> <world> <1234567890>\0"
wonderer
Are you writing strlen(string) bytes? If so, strlen() does not include the '\0', so you need to add one to the count there.
Jonathan
got it. thanks!
wonderer