Symentic Mistakes to review

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
SemiconductorCat
Major
Major
Posts: 455
Joined: Mon Aug 22, 2011 8:42 pm
Location: currently in hyperspace

Symentic Mistakes to review

Post by SemiconductorCat » Sun Feb 03, 2013 7:06 am

hi all, I'm going to make a list of syntatic mistakes that you have made during programming with C++,
So other's also could review them and learn from these.

Feel free to add your mistakes.

Here are the mistakes that I done today,

[ *] Using 'strncpy' instead of 'memcpy' when copying binary objects.
In the documentation strncpy said that it stops copying source to the destination when one of bellow two
condition(s) met.
* if number of characters copied were equal to 'n'.
* if it found NULL character '\0' in the source string before copying n strings.
So it's clear that you could not use strncpy there to copy a binary data structure. So the solution is to
use 'memcpy()'.

Code: Select all


    while( SQLITE_ROW == sqlite3_step(search_stmt ) )
	{
	  // print the record //
	  const int  index_value = sqlite3_column_int(search_stmt,0);
	  void* object = (void*)sqlite3_column_blob(search_stmt,1);
	  //int size = sqlite3_blob_bytes(object);
	  char *buffer=  new char[sizeof(MY_STRUCT)] ;  
	  strncpy(buffer,(char*)object,sizeof(MY_STRUCT));// why this fails to work ?
	  MY_STRUCT *ptr_myStruct = (MY_STRUCT*) buffer;  
	  printf( "index :%d and string:%s \n",index_value,ptr_myStruct->buffer);
	}


[*] Use sizeof incorrectly.
I have some structure called 'MY_STRUCT' and it's size is 200 bytes. But sizeof(MY_STRUCT*) is just 4 or 8
bytes depending on your computer architecture.

Code: Select all

  	MY_STRUCT * my_struct = populate_my_struct(i,i+1,insert_string);

	rc =sqlite3_bind_blob(insert_stmt,2,my_struct,sizeof(my_struct),SQLITE_TRANSIENT); 

  
see the mistake? Then my blob object will be only 8 bytes long(since I'm on x64).
Post Reply

Return to “C/C++ Programming”