user5979025
user5979025

Reputation:

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

I have a var called DirToEmpty which holds the path to the temp dir.

I have another var called TempBufDir which will be holding the same value as of DirToEmpty but with 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, I malloc'd TempBufDir, and tried copying each char from DirToEmpty into TempBufDir.

Here's the code:

// Count number of backslashes
int backslashes = 0;
for (int i = 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;
}

for (int i = 0, j = 0; *(DirToEmpty)+i; i++, j++) {

    // Copy the char
    *(TempBufDir + i) += *(DirToEmpty + j);

    // If the char is a backslash, add another one to escape it
    // If kth element is a backslash, k+1th element should also be a backslash
    if (*(DirToEmpty + j) == TEXT('\\')) {
        *(TempBufDir + (i + 1)) = TEXT('\\');
    }
}

However, the program seems to crash as soon as I execute the program.

See the screenshot at the bottom of the post.

EDIT : Program seems to quit fine if I remove the last for loop. So I assume it's related to the buffer size?

EDIT 2 : I changed the 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

Upvotes: 0

Views: 183

Answers (1)

Carlos A. Ibarra
Carlos A. Ibarra

Reputation: 6142

In addition to the needed doubling of the malloc parameter, there are a bunch of bugs in that loop,

  • Inconsistent use of i and j as source and destination indexes
  • Wrong loop condition
  • Spurious +=
  • Forgot to increase i when adding an extra \
  • Needs to add 0 terminator

Here is my attempt to fix it:

for (int i = 0, j = 0; *(DirToEmpty+j); i++, j++) {
    *(TempBufDir + i) = *(DirToEmpty + j);

    if (*(DirToEmpty + j) == TEXT('\\')) {
        *(TempBufDir + (i + 1)) = TEXT('\\');
        i++;
    }
}
TempBufDir[i] = 0;

By the way, in C, if p is a pointer and i is an integer, *(p+i) is the same as p[i]. You should be using DirToEmpty[i] and not *(DirToEmpty+1).

Upvotes: 1

Related Questions