-
malloc/free behavior
Code:
char *query;
for(i=0;i<sizeof(tables)/sizeof(char *);i++)
{
query=malloc(39-sizeof(tables[i]));
sprintf(query,"delete from %s where rowid=$1::int8;",tables[i]);
printf("%s\n",query);
//free(query);
}
}
I've read somewhere that with every call to malloc there should be one to free. Why does above code fails if free is uncommented?
-
Perhaps because you're causing a buffer overrun?
-
You are right. I change 39 to 41 and it works.
-
correct thing should have been 35+sizeof
-
Note that I would do something like:
Code:
const char query_[] = "delete from where rowid=$1::int8;"
query=malloc(sizeof(query_)+strlen(tables[i]) /* null terminator counted because of sizeof */);
sprintf(query,"delete from %s where rowid=$1::int8;",tables[i]);
printf("%s\n",query);
I don't know what table[i] is, though. It may be a mere char pointer, so I used strlen. If it's an array in the local function, you may use sizeof. Otherwise you cannot.
This should ensure you have enough space.
I doubt that your calculation is anywhere near right.
-
looks better since it does not use magic number.
-
Don't forget to check the returned pointer from malloc against NULL!