Skip to content

Commit

Permalink
writeANSI: use strcpy instead of strncat
Browse files Browse the repository at this point in the history
strncat(3) needs to traverse through the buffer to append the string
into the end of old string. This will have a big performance penalty
when we have a very large input.

Replace it with strcpy(3) and a pointer to track the end of current
buffer.

Accidently, this change also silence gcc's -Wstringop-overflow warning,
since gcc thinks our issue to strncat(3) to stop right at the NULL
terminator maybe an error.
  • Loading branch information
sgn committed Dec 12, 2019
1 parent 029ca3b commit 7cee9f4
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions qrenc.c
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,12 @@ static void writeANSI_margin(FILE* fp, size_t realwidth,
}
}

#define CPY_ADV_BUF(BUF, STR)\
do {\
strcpy(BUF, STR);\
BUF += strlen(STR);\
} while (0)

static int writeANSI(const QRcode *qrcode, const char *outfile)
{
FILE *fp;
Expand All @@ -750,7 +756,8 @@ static int writeANSI(const QRcode *qrcode, const char *outfile)

const char *white, *black;
char *buffer;
size_t white_s, black_s, buffer_s;
char *pbuf;
size_t white_s, buffer_s;

if (image_type == ANSI256_TYPE) {
/* codes for 256 color compatible terminals */
Expand All @@ -761,7 +768,6 @@ static int writeANSI(const QRcode *qrcode, const char *outfile)
black = "\033[40m";
}
white_s = strlen(white);
black_s = strlen(black);

size = 1;

Expand All @@ -784,32 +790,33 @@ static int writeANSI(const QRcode *qrcode, const char *outfile)
row = p + (y * qrcode->width);

memset(buffer, 0, buffer_s);
strncpy(buffer, white, white_s);
pbuf = buffer;
CPY_ADV_BUF(pbuf, white);
for (x = 0; x < margin; x++) {
strncat(buffer, " ", 2);
CPY_ADV_BUF(pbuf, " ");
}
last = 0;

for (x = 0; x < qrcode->width; x++) {
if (row[x] & 0x1) {
if (last != 1) {
strncat(buffer, black, black_s);
CPY_ADV_BUF(pbuf, black);
last = 1;
}
} else if(last != 0) {
strncat(buffer, white, white_s);
CPY_ADV_BUF(pbuf, white);
last = 0;
}
strncat(buffer, " ", 2);
CPY_ADV_BUF(pbuf, " ");
}

if (last != 0) {
strncat(buffer, white, white_s);
CPY_ADV_BUF(pbuf, white);
}
for (x = 0; x < margin; x++) {
strncat(buffer, " ", 2);
CPY_ADV_BUF(pbuf, " ");
}
strncat(buffer, "\033[0m\n", 5);
CPY_ADV_BUF(pbuf, "\033[0m\n");
fputs(buffer, fp);
}

Expand Down

0 comments on commit 7cee9f4

Please sign in to comment.