I apologize in advance for the useless title of this question, but nothing seemed to fit better.
The idea here is to replicate argv
in another variable, essentially making a copy of it. So the basic idea of what the function does is, use malloc()
to request some space for a copy and then iterate through argv
making copies of each element.
This is the code I'm working with, the development environment is right now Visual Studio 2019 (even if it's not strictly a C compiler...):
// Returns a copy of an array of strings (intended for argv, but should work with any of them):
wchar_t** copyArgv(size_t argc, wchar_t* argv[]) {
// Allocate space for the array of arguments:
wchar_t** argsCopy = malloc(((argc + 1) * sizeof(wchar_t*)));
if (!argsCopy)
return NULL;
// Copy each one of them:
for (size_t i = 0; i < argc; i++) {
argsCopy[i] = _wcsdup(argv[i]);
if (!argsCopy[i]) {
// Should also free any previous copied string I left that part out in the paste.
free(argsCopy);
return NULL;
}
}
argsCopy[argc] = NULL;
return argsCopy;
}
I've been trying different ways to make a copy of argv but each and everyone of them lets VS to believe there can be a buffer overrun when I make a copy of an argument (line:argsCopy[i] = _wcsdup(argv[i]);
) or reading invalid data in the next line, meaning reading out of the bounds of the reserved space.
All of this has lead me to believe the problem lies in the (now) only malloc()
call to reserve space for the array of arguments.
Yet I'm banging my head against the wall trying to figure out what the problem is, I mean, I think I'm asking for enough space.
I've tried other compilers as well, latest stable versions of Clang and GCC don't seem to show any such warning. So I decided to ask you, seasoned programmers, if you can spot the problem, or it's some sort of compiler bug (unlikely I bet).
For reference these are the exact warnings VS2019 is throwing (in a 64-bit compilation):
In the assignment:
Buffer overrun while writing to 'argsCopy': the writable size is '((argc+1))*sizeof(wchar_t *)' bytes, but '16' bytes might be written.
Next line, the test for NULL:
Reading invalid data from 'argsCopy': the readable size is '((argc+1))*sizeof(wchar_t *)' bytes, but '16' bytes may be read.