Avoid using strcpy
, unless you are absolutely sure you have enough space in the target array.
Try this for a safe version. It still works quite bad, because lang
probably does not fit, but it is safe.
char global[] = " ";
// alternative 1
snprintf(global, sizeof global, "%s", lang);
// alternative 2, more lines but also slightly more efficient
global[0] = 0;
strncat(global, lang, (sizeof global) - 1); // -1 needed to allow room for '\0'
For reference, man pages of snprintf
and strncat
.
To solve the space issue, you should probably make global
big enough to hold all possible lang
strings, if you know the limit and it is reasonably small:
char global[16] = ""; // room for 15 characters, contents initialized to all 0
snprintf(global, sizeof global, "%s", lang);
Alternative is to use dynamic memory:
int bufsize = strlen(lang) + 1;
char *global = malloc(bufsize); // contents uninitialized
// can't use sizeof, it would give size of pointer, not allocated buffer
snprintf (global, bufsize, "%s", lang);
...
free(global); global = NULL;
For using dynamic memory, also check out asprintf
, documented in same man page as snprintf
(link above).
You can also consider using Variable Length Arrays of C99, though if variable name is global
, it will probably not work for your case:
char global[strlen(lang) + 1] = ""; // +1 for '\0', contents initialized to all 0
snprintf (global, sizeof global, "%s", lang); // now sizeof works again
// global is unallocated when it goes out of scope
Note that with dynamic memory, where you allocated enough memory for current contents of lang
, you could use strcpy
too, because then it is a case where you do know it fits safely. Still, using safe versions may be more robust against future modifications introducing new bugs.