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);
}
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);