chaitanya sonagara
chaitanya sonagara

Reputation: 392

Is there any way to find Dynamic memory size like sizeof facelity?

I am looking for something which give me size which taken by str character pointer.

int main()
{
    char * str = (char *) malloc(sizeof(char) * 100);
    int size = 0;
    size  = /* library function or anything use to find size */
    printf("Total size of str array - %d\n", size);
}

I want prove that give memory is 100 bytes. Is any one have any idea about this ?

Upvotes: 1

Views: 91

Answers (3)

John Bode
John Bode

Reputation: 123558

There is no (good, standard, portable) way to tell from a pointer value alone whether it's the first element of an array or not, nor how many elements follow it. That information has to be tracked separately.

If you're writing in C++, don't do your own memory management if you can help it. Use a standard container type like std::vector or std::map (or std::string for text). If you must do your own memory management, use the new and delete operators instead of the *alloc and free library functions, and wrap a class around those operations that also keeps track of how many elements have been allocated (which, like std::vector and std::map, is returned via a read-only size() method).

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 223747

  1. The C and C++ standards do not provide a way to get, from an address, the amount of memory that was requested in the call to malloc that returned that address.

  2. Some C or C++ implementations provide a way to get the amount of memory that was provided at the given address, such as malloc_size. The amount provided may be greater than the amount that was requested.

  3. If the memory contains a string, which is an array of characters terminated by a null character, then you can determine the length of the string by counting characters up to the null character. This function is provided by the standard strlen function. This length is different from the space allocated unless, of course, the string happens to fill the space.

Upvotes: 2

Jesper Juhl
Jesper Juhl

Reputation: 31458

A raw pointer only knows it points to a single element of it's type. If that thing it points to happens to be part of an array, the pointer doesn't know and there's no way to get that information from it.

You want to instead use types that do know their size, like for example; std::string, std::array or std::vector.

Upvotes: 2

Related Questions