In order to generate filenames I need to provide some buffer memory for sprintf. The size of these buffers was chosen rather arbitrarily in the past. This can easily lead to very nasty stack overflow bugs in the future, when e.g. int becomes 64bit long but the string buffer size was chosen to be 10 characters only as this is the maximum amount of digits a 32 bit int can hold.
Some MWE:
for (int i = 0; i < mpi_size; i++) {
//magic number: 32bit integer has 10 digits,
//+6 for "/rank_", +1 for null termination
char path2[strlen(path) + 17];
//This can possibly be an access violation, or a very hard to
//find bug:
sprintf(path2, "%s/rank_%d", path, i);
//Using path2 to access some file
}
Completely different sizes where chosen in other places, were people were very sure, that the int will not be bigger than e.g. 3 digits. This can lead to problems much easier.
What would be a perfect and portable solution?
I found the function g_printf_string_upper_bound in the gnome library which would solve this problem elegantly and reliably.
Is there anything like this in the C standard, in POSIX or somewhere else?
Aucun commentaire:
Enregistrer un commentaire