Wolfgang Rohdewald wrote:
My problem code:
mgDb::Build_cddbid(const mgSQLString& artist) const { char *s; asprintf(&s,"%ld-%.9s",random(),artist.original());
segfaults only if illegal utf8 chars appear in artist.original()
asprintf returns -1, so s is nothing that could be freed, and this gives a nice backtrace:
Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1319449712 (LWP 22989)] 0xb7bf57ea in free () from /lib/tls/i686/cmov/libc.so.6 (gdb) bt #0 0xb7bf57ea in free () from /lib/tls/i686/cmov/libc.so.6 #1 0xb7986908 in mgDb::Build_cddbid (this=0x86ed8e8, artist=@0xb15aa698) at mg_db.c:1023
As you can see it doesn't segfault on asprintf but on free().
If I change %.9s to %s, everything is fine.
I cannot easily simplify that, if I try like this, it works:
char artist[50]; strcpy(artist,"Celine Dion"); artist[1]=0xe9; asprintf(&buffer,"%ld-%.9s",random(),artist); printf(buffer); free(buffer);
if(asprintf(...) >= 0) { printf(...); free(...); }
Or just use normal snprintf as the amount of charactes to print is fixed anyways so you don't need a variable sized buffer.
cu Ludwig