Hi Folks,
I have written a read function which reads values from serial port(LINUX) . It returns values as pointer to char . I am calling this function in another function and storing it again in a variable as pointer to char . I occasionally got stack over flow problem and not sure if this function is creating problem.
The sample is provided below. Please give some suggestions or criticism .

char *ReadToSerialPort( )
{
	 const int buffer_size = 1024;
	 char *buffer = (char *)malloc(buffer_size);
	 char *bufptr = buffer;
     size_t iIn;
    int iMax = buffer+buffer_size-bufptr;
    if ( fd < 1 )
    {
        printf( "port is not open\n" );
       // return -1;
    }

    iIn = read( fd, bufptr, iMax-1 );
    if ( iIn < 0 )
    {
    	if ( errno == EAGAIN )
    	{
    		printf( "The errror in READ" );
    		return 0; // assume that command generated no response
    	}
    	else
    		printf( "read error %d %s\n", errno, strerror(errno) );

   }
   else
   {
	  // *bufptr = '\0';
	   bufptr[(int)iIn<iMax?iIn:iMax] = '\0';
	   if(bufptr != buffer)
	      return bufptr;
   }
    free(buffer);
  return 0;

} // end ReadAdrPort
int ParseFunction(void)
{
 // some other code
char *sResult;
if( ( sResult = ReadToSerialPort()) >= 0)
{
  printf("Response is %s\n", sResult);

// code to store char in string and put into db .
}

}

I think you probably want line 29 to be bufptr[ (int)iIn < iMax ? iIn : iMax - 1 ] = '\0'; instead of bufptr[ (int)iIn < iMax ? iIn : iMax ] = '\0'; The way you have it at the moment will occasionally try to write to bufptr[iMax] , which is guaranteed to be 1 past the end of bufptr . You have to include the \0 character in the length of your string.

Also, why do you do int iMax = buffer+buffer_size-bufptr; on line 7? Since you say char *bufptr = buffer; immediately before, then iMax is always guaranteed to be equal to buffer_size , right?

I guess, ur statement makes sense.Thanks for pointing. I will try t implement or may be use vectors.. I will update you guys soon . Thanks for all help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.