c++ - Windows malloc issue? -
in windows (visual studio c++ 2010) i'm trying simple string copy. here's code:
char * filename; (...) filename = (char *) malloc(wcslen(argv[(i + 1)]) + 1); wcscpy((wchar_t *)filename, argv[i + 1]); wprintf(l"filename is: %s", filename);
and program crashes if argv[i + 1] if bigger 14. if 14 or less runs fine. see bellow.
c:\visual studio 2010\projects\test\release>test.exe -f 12345678901234 aa asas asas first argument argv[1] -f argc = 6 filename is: 12345678901234
what's gotcha here? missing? thanks.
realise wcslen()
returns number of wide characters in string, not number of bytes occupies. , malloc()
requires number of bytes...
so need multiply number of wide characters size of wide character before passing malloc()
:
filename = (char *) malloc( (wcslen(argv[(i + 1)]) + 1) * sizeof(wchar_t));
but then, you're typecasting (char *)
. if argv
declared char *argv[]
or char **argv
, wcslen()
wrong function use anyway: need strlen()
.
Comments
Post a Comment