DEV Community

Discussion on: SQL, strcat(), and more segmentation fault

Collapse
 
ac000 profile image
Andrew Clayton

Quick tip.

strcat(3) should generally be avoided, unless you know 100% everything will fit.

Instead, in this case it would be better to use snprintf(3), though you can still get string truncation, or if you have GNU extensions you can use asprintf(3), which is like sprintf(3) but dynamically allocates the buffer.

Using snprint(3), your block of strcat()'s and malloc() can be reduced to...

#include <stdio.h>
...
char dsn[BUF_SZ];

snprintf(dsn, sizeof(dsn), "DSN=%s;UID=%s;PWD=%s",
         argv[1], argv[2], argv[3]);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tardisgallifrey profile image
Dave

Freaking brilliant! Worked like a charm, easier to read and configure. That's why I'm a noob.

Thanks,

Collapse
 
ac000 profile image
Andrew Clayton

Cool, no problem!

Collapse
 
tardisgallifrey profile image
Dave

Thanks, I'll have to give that a try.