c - Unable to copy a wchar_t's contents into another wchar_t var which was malloc'd? -


i have var called dirtoempty holds path temp dir.

i have var called tempbufdir holding same value of dirtoempty backslashes escaped.

example of expected behavior:

wchar_t dirtoempty[max_path] = text("c:\xxx\yyy\zzz"); wchar_t tempbufdir[max_path] = text("c:\\xxx\\yyy\\zzz"); 

for this, malloc'd tempbufdir, , tried copying each char dirtoempty tempbufdir.

here's code:

// count number of backslashes int backslashes = 0; (int = 0; *(dirtoempty + i); i++) {     if (*(dirtoempty + i) == text('\\')) {         backslashes += 1;     } }  // size of tempbufdir = length of dirtoempty + backslashes(escaped) + 1 size_t lpbufsize     = wcslen(dirtoempty) + backslashes + 1; wchar_t * tempbufdir = (wchar_t *) malloc (lpbufsize);  if (tempbufdir == null) {     return 9; }  (int = 0, j = 0; *(dirtoempty)+i; i++, j++) {      // copy char     *(tempbufdir + i) += *(dirtoempty + j);      // if char backslash, add 1 escape     // if kth element backslash, k+1th element should backslash     if (*(dirtoempty + j) == text('\\')) {         *(tempbufdir + (i + 1)) = text('\\');     } } 

however, program seems crash execute program.

see screenshot @ bottom of post.

edit : program seems quit fine if remove last for loop. assume it's related buffer size?

edit 2 : changed malloc line to:

wchar_t * tempbufdir = (wchar_t *) malloc (lpbufsize * sizeof(wchar_t));

this hasn't changed anything. program still crashes.

edit 3 :

enter image description here

in addition needed doubling of malloc parameter, there bunch of bugs in loop,

  • inconsistent use of , j source , destination indexes
  • wrong loop condition
  • spurious +=
  • forgot increase when adding \
  • needs add 0 terminator

here attempt fix it:

for (int = 0, j = 0; *(dirtoempty+j); i++, j++) {     *(tempbufdir + i) = *(dirtoempty + j);      if (*(dirtoempty + j) == text('\\')) {         *(tempbufdir + (i + 1)) = text('\\');         i++;     } } tempbufdir[i] = 0; 

by way, in c, if p pointer , integer, *(p+i) same p[i]. should using dirtoempty[i] , not *(dirtoempty+1).


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -