Michael Thomas
Michael Thomas

Reputation: 503

Bad Pointers and Garbled Data

Forgive me if I might sound stupid, but I'm a Bio major student who ended up working in software development (never had a single subject on coding). So coding isn't in my forte, but I really want to learn.

Now that that's out of the way: Pointers.

I'm writing an application in Visual C++ for serial communication and have spent the last three days struggling to output the right data.

This is the relevant code block:

//The ports have been opened, data has been written and the  rest follows
//Initialising buffer

DWORD dwBytesRead = 0;
BYTE*  abBuffer = NULL; // Instance 1


do
{
    // Read data from the COM-port
    serial2.Read(&abBuffer,sizeof(&abBuffer),&dwBytesRead); // Instance 2
    if (dwBytesRead > 0)
       {
        CString a=(LPCTSTR)&abBuffer;//To check what is being read        
        SetDlgItemText(IDC_RECV,(LPCTSTR)&abBuffer);


}
else
MessageBox("No");
}
while (dwBytesRead == sizeof(&abBuffer));
//delete[] abBuffer; 
//Close the port again

While debugging I can see that at Instance 1 "abBuffer" is

abBuffer 0xcccccccc unsigned char *

and at Instance 2 it is

abBuffer 0x00000000 unsigned char *

I know that the value at instance 1 is a mode code used because I put a breakpoint before that line and 2 is NULL, but why the bad pointer?

Also the data I'm receiving is acting weird.

Try 1:

Sent data : "hi"

Received data : "hiÜÜÌÌÌÌÌÌÌÌ"

Try 2:

Sent data : "hihihi"

Received data : "hiÜÜÌÌÌÌÌÌÌÌ"

Try 3: To check which end of the data is being cut of

Sent data : "aibicidi"

Received data : "cidiÌÌÌÌÌÌÌÌ"

else clause triggered WHY?

Try 4: To check what the cut off is, turns out it is 4 bytes

Sent data = "mike"

Received data = "mikeÌÌÌÌÌÌÌÌ"

else clause triggered

Any ideas why my data might be getting garbled?

There are three main questions, but they are related so that's why I'm here.

Help?

Upvotes: 0

Views: 180

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

You have multiple problems. To start with abBuffer is a null pointer. You can not write data to where it's pointing. Secondly, &abBuffer gives you a pointer to the variable abBuffer.

The solution to the first problem is to allocate memory for abBuffer to point to. This is simplest done by using an array instead of a pointer.

The solution to the second problem is to not use the address-of operator, but plain abBuffer.

Upvotes: 1

Related Questions