I have a function that I query my database:
void update_layout_database()
char query[255];
MYSQL_ROW row;
float wd,ht;
sprintf(query,"SELECT name,wd,ht FROM pagelayouts WHERE drawing=%s AND handle=%ld;",drawing_number,layoutID);
mysql_query(sqlconnect,query);
MYSQL_RES *result = mysql_store_result(sqlconnect);
row=mysql_fetch_row(result);
if(row!=NULL){
if(atof(row[1])==0 || atof(row[2])==0 || !strcmp(row[0],"Model")){
wd=Extents[2]-Extents[0];
ht=Extents[3]-Extents[1];
sprintf(query,"UPDATE pagelayouts SET X=%f, Y=%f,wd=%f,ht=%f WHERE drawing=%s AND handle=%ld",Extents[0],Extents[1],wd,ht,drawing_number,layoutID);
mysql_query(sqlconnect,query);
}
}
}
Variables sqlconnect, drawing_number, layoutID and Extents are global declared in the root of the script.
MYSQL *sqlconnect=NULL;
char * drawing_number, layoutID;
float Extents[4]={0,0,0,0};
The database is intialised:
void initialize_database(char *dBase)
{
char * Dname=(char *)malloc(strlen(dBase+2));
sprintf(Dname,"prefix%s",dBase);
sqlconnect=mysql_init(sqlconnect);
if (!mysql_real_connect(sqlconnect, "localhost", "dgman", "xxxxxxxxxxxxxxx", Dname, 0, NULL, 0))
{
fprintf(stderr, "Unable to connect to MariaDB servern");
exit(1);
}
mysql_set_character_set(sqlconnect, "utf8");
}
According to GDB, the value of ‘sqlconnect’ is properly instantiated:
The same screenshot shows the contents of the ‘query’ string.
I’m baffled.
Can anyone suggest how I can solve this?
2
Answers
You have a crash inside
malloc
implementation.99.999% of such crashes are caused by heap corruption (heap buffer overflow, freeing something twice, freeing unallocated memory, etc. etc.).
These bugs are ~impossible to find without proper tools, because the bug often manifests itself in a place that is far removed from where the actual problem occurs.
Fortunately we do have tools which help you find the root cause: Valgrind and Address Sanitizer.
Use them and you will likely be pointed straight at the problem.
P.S. You should never use
sprintf
— it’s a recipe for buffer overflow. Always usesnprintf
instead.strlen("prefix") + the null is > 2