0
char* pszBuffer = NULL, * pszNewBuffer = NULL;

    pszBuffer = (char*)malloc(24);
    **sprintf_s(pszBuffer, sizeof(pszBuffer), "%s", "TestString");**

    printf("[%p] %u %s\n",
        pszBuffer, _msize(pszBuffer), pszBuffer);

In this code, "buffer is too small". what problem is this?

When I changed from "sizeof(pszBuffer)" to "24(just number size)", it can run. so I think, sprintf_S function can not use sizeof. Am I right?

nub
  • 1
  • 1
    `sizeof(pszBuffer)` is the size of the pointer, not the amount of memory it points to. Usually 4 or 8 depending on platform. If instead you didn't use dynamic allocation and had something like `char buffer[24];` then `sizeof(buffer)` would be 24. – Retired Ninja Feb 21 '23 at 05:07
  • `sizeof(pszBuffer)` is the size of the pointer. Not the size of allocated memory – kuro Feb 21 '23 at 05:08
  • add `printf("%d", sizeof(pszBuffer));` and see what you get – pm100 Feb 21 '23 at 05:10
  • @pm100 `%d` for `sizeof()`?!?!?! – Andrew Henle Feb 21 '23 at 09:16

1 Answers1

0

Since the array referenced by pszBuffer is allocated via malloc() at runtime, the compiler can't know its size.

Here, sizeof(pszBuffer) is the size of the pointer variable itself, which is most likely 4 bytes or 8 bytes, hence the "buffer is too small" error.

jyl
  • 401
  • 3
  • 12