0

I'm wondering why, when I run the following code, the value of t is the same after the call to get as it was before.

I have a feeling that the issue is the reassignment in line 11, at c = tmp - But hopefully someone can point me in the right direction?

#include <stdio.h>
#include <tchar.h>
#include <windows.h>

BOOL get(COMPUTER_NAME_FORMAT f, WCHAR* c) {
    DWORD s = 0;
    WCHAR* tmp = NULL;
    GetComputerNameExW(f, tmp, &s);
    tmp = (WCHAR*)realloc(tmp, sizeof(WCHAR) * s);
    GetComputerNameExW(f, tmp, &s);
    c = tmp;
    return TRUE;
}

void _tmain(int argc, _TCHAR* argv[])
{

    WCHAR* t = TEXT("thisisatest");
    BOOL res = get(ComputerNameDnsHostname, t);
    printf("%Ls\n", t);
}

The above code have, for the sake of brevity, been stripped of error handling code. Also, I suspect there's a race condition between the 2 calls to GetComputerNameExW().

MadsRC
  • 197
  • 1
  • 12
  • Assigning a new value to a function's parameter has no effect outside of that function. (What do you expect to happen if you call `get(ComputerNameDnsHostname, 0)`? Would the value of `0` change?) – molbdnilo Nov 28 '18 at 08:15
  • 2
    There can't be a race condition with synchronous calls in a single-threaded program. – molbdnilo Nov 28 '18 at 08:16
  • 1
    Look at the signature of `realloc` closely. Note how it returns a new pointer. Have you ever wondered why it's needed? – n. m. could be an AI Nov 28 '18 at 08:17
  • @George "*The length of the name may be greater than `MAX_COMPUTERNAME_LENGTH` characters because DNS allows longer names. To ensure that this buffer is large enough, set this parameter to `NULL` and use the required buffer size returned in the `lpnSize` parameter.*" – melpomene Nov 28 '18 at 08:23
  • is second GetComputerNameExW function and realloc For Exception Handling? example memory leak or don't believe win api.. I don't understand – sangho Nov 28 '18 at 08:49

1 Answers1

1

You are simply modifying the parameter copy of main's t pointer within the get(COMPUTER_NAME_FORMAT f, WCHAR* c) function.

The effect is not propagated outside get. You are assigning the value of tmp to a temporary pointer that is lost after get returns.

Pass c as WCHAR** c in get as follows:

BOOL get(COMPUTER_NAME_FORMAT f, WCHAR** c){
  //stuff
  tmp = (WCHAR*)realloc(tmp, sizeof(WCHAR) * s);
  *c=tmp;
  //other stuff
}
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
  • So when passing in WCHAR* t as WCHAR* c in get, I'm just passing in the address of t as c and then later replacing said address with the address of WCHAR* tmp (Which, now that I think of it, I know...) So using a pointer to a pointer would fix it, as I'd just replace the second-level pointer that the first-level pointer points to... I could live with that... – MadsRC Nov 28 '18 at 08:39
  • 1
    Correct, but `t` itself is never modified. – Davide Spataro Nov 28 '18 at 08:40