0

Consider the following case:

int MyClass::MyMethod(char *myChar)

Am I able to get the amount of reserved space by myChar within memory (heap and stack) ? For example, if myChar points to the first element of an array called char myArray[10]: By use of myChar, can I get the amount of char that can be stored within myArray?

  • 3
    why do you need it? Sounds like a [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). It cannot be done in standard c++ btw – 463035818_is_not_an_ai Dec 07 '20 at 11:00
  • I need to find memory leaks caused by an Trim Method. Its important whether a string has a size, of x, or it has a size of 0 , while the array reserves space for 10 chars. –  Dec 07 '20 at 11:04
  • Strangely closely realted it seems: https://stackoverflow.com/questions/65109114/avoiding-the-funcchar-api-on-embedded/65178718#65178718 – Yunnosch Dec 07 '20 at 11:19
  • I don't really get it. Why don't you just reproduce the memory leak by passing in an array of the size you need to do so? Then you'll already know what the size is... If the function breaks when you pass some other size, then pass _that_ size and debug/fix the problem. – Asteroids With Wings Dec 07 '20 at 11:21
  • Did you mean to use `string_view` or `span`? – Surt Dec 07 '20 at 11:58

1 Answers1

0

By use of myChar, can I get the amount of char that can be stored within myArray?

In general no, there is no way to get the size of an array from just knowing a pointer to (first) element of that array.

If you know something special about the contents of the array, then it may be possible. For example, it is quite common for character strings to be in a null terminated array where the null character is the last element of the array In such case, you can count the number of elements until you reach the terminator. There are standard functions for this purpose.

eerorika
  • 232,697
  • 12
  • 197
  • 326