0

I want to add a string after the struct in memory. How to check that i dynamically allocated right amount of bytes?

Example:

 const wchar_t* add_str = L"test string"; struct test_{ wchar_t* name; size_t namelen; } test; void* ptest_void = malloc(sizeof(test) + wcslen(add_str)*sizeof(wchar_t)); // i cant dereference void*, hence, cant check sizeof(*ptest_void) // then i try to get sizeof of a ptr which was cast to (test_*): test_* ptest = (test_*)ptest_void; size_t ptest_sz = sizeof(*ptest); // ptest_sz has the size of _test struct, but without size of add_str... free(ptest_void); 
14
  • 7
    sizeof(pointer) returns size of pointer, not the content it points to. Commented Aug 18, 2022 at 12:05
  • it was a typo, i edited the question the now there is sizeof(*ptest) Commented Aug 18, 2022 at 12:08
  • also this code supose to be C or C++? There is a difference how it should look like. Commented Aug 18, 2022 at 12:08
  • Don't use malloc/free in C++. Use new/new[]/delete/delete[] if you must, but in general try to avoid manual memory management entirely. Use containers first, smart pointers if you have to, raw manual memory management almost never. Commented Aug 18, 2022 at 12:09
  • 1
    As @JesperJuhl said: Use STL containers (std::vector, std::string) first. Then only if you really have to write your own datastructure prefer using std::make_unique/std_unique_ptr (or std::make_shared/std::shared_ptr if you have good enough design reasons to do so). Check it here (I don't think I needed new/delete anymore ever since C++11 came out): isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines Commented Aug 18, 2022 at 12:19

1 Answer 1

5

sizeof(ptest) doesn't tell you how much allocated memory ptest points to. It tells you the size in bytes of the variable ptest, most likely either 4 or 8 depending on your system.

There's also no standard way to check "how big" an allocated block of memory it. You're expected to keep track of that yourself.

If a call to malloc does not return NULL, that means the call was successful, and you can access as many bytes as you told it to allocate.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.