strcat problem

A

arssa2020

hello all,

ms visual studio 2003,
i need to read serial bytes (one byte at a time) from serial port, and
the catenate it to a char* (cannot use strings)
strcat require that the 2nd parameters (the src)to be of type
const char*.
so i cast the (char byte) to be a (char*)

i have the following code
char byte;
char s[128]
.....
//read serial data from serial port
ReadFile (hPort, &byte, 1, &dwBytesTransferred, 0);
....
if(byte !=0x0D) //CR
{
//append the received byte to the string s
strcat(s,(char*)byte)
}

//it gives me access violation
"Unhandled exception at 0x00420601 in Test.exe: 0xC0000005: Access
violation reading location 0x00000047."

how can i go around it?
i cannot use string class members..
thanks
 
C

Carl Daniel [VC++ MVP]

hello all,

ms visual studio 2003,
i need to read serial bytes (one byte at a time) from serial port, and
the catenate it to a char* (cannot use strings)
strcat require that the 2nd parameters (the src)to be of type
const char*.
so i cast the (char byte) to be a (char*)

No, you most certainly cannot.
i have the following code
char byte;
char s[128]
....
//read serial data from serial port
ReadFile (hPort, &byte, 1, &dwBytesTransferred, 0);
...
if(byte !=0x0D) //CR
{
//append the received byte to the string s
strcat(s,(char*)byte)
}

//it gives me access violation
"Unhandled exception at 0x00420601 in Test.exe: 0xC0000005: Access
violation reading location 0x00000047."

Naturally. You're trying to access an address on 0x00000000 .. 0x000000ff,
all of which are in the protected page at the botttom of the address range.
how can i go around it?
i cannot use string class members..

Why not?

Anyway, try something like this:

<code>
char s[128] = {0};
int length = 0;
.....
//read serial data from serial port
ReadFile (hPort, &s[length], 1, &dwBytesTransferred, 0);
....
if(byte !=0x0D) //CR
{
length++;
}
</code>

using strcat to append a single byte is quite a waste of effort when you can
just read the byte into the right place to start with.

Be sure to protect against buffer overflow (i.e. make sure length is always
<=127 and handle appropriately if it tries to go out of bounds).

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top