2

I have been using this code:

char options_string[96];
sprintf(options_string,"%s_G%u", options_string, options.allowed_nucleotide_gap_between_CpN);

which is just writing unsigned integers to a string mixed with some letters.

but with the new version 9 of GCC that I just started using, is warning me:

warning: passing argument 1 to restrict-qualified parameter aliases with argument 3 [-Wrestrict] 1012 |
sprintf(options_string,"%s_G%u", options_string, options.allowed_nucleotide_gap_between_CpN); | ^~~~~~~~~~~~~~ ~~~~~~~~~~~~~~

I've read that the best way to make a string like this is to use sprintf, as I have: How to convert an int to string in C?

I've re-checked the code, and I'm not using any restrict keywords.

How can I write to this string without the warning?

con
  • 5,767
  • 8
  • 33
  • 62

3 Answers3

5

The code causes undefined behaviour because the same part of a char buffer is used as both input and output for sprintf. The warning is useful information in this case. To be correct you must change the code so there is no overlap between inputs and outputs.

For example you could find the end of the current string and start writing from there. Also it would be wise to guard against buffer overflows in the length of output.

Possible code:

char options_string[96];
// ...assume you omitted some code that writes some valid string

size_t upto = strlen(options_string);
int written = snprintf(options_string + upto, sizeof options_string - upto,
    "_G%u", options.allowed_nucleotide_gap_between_CpN);
if ( written < 0 || written + upto >= sizeof options_string )
{
     // ...what you want to do if the options don't fit in the buffer
}
M.M
  • 138,810
  • 21
  • 208
  • 365
3

A conforming implementation of sprintf could start by writing a zero byte to the destination, then replacing that byte with the first byte of output (if any) and writing a zero after that, then replacing that second zero byte with the next byte of output and writing a third zero, etc. Such an approach would avoid the need to have it take any particular action (such as writing a terminating zero) after processing the last byte. An attempt to use your code with such an implementation, however, would fail since options_string would effectively get cleared before code could read it.

The warning you're receiving is thus an indication that your code may not work as written.

supercat
  • 77,689
  • 9
  • 166
  • 211
0

In your case it is better to use the strcat function instead of sprintf, due to the fact that you want to concatenate a string.