How to determine the size of the allocated buffer C?

I have a buffer and you want to do a test to see if the buffer has enough capacity Ie find the number of elements that I can add to the buffer.

char *buffer = (char *)malloc(sizeof(char) * 10); 

Performance

 int numElements = sizeof(buffer); 

doesn't return 10, any ideas on how I can do this?

+7
source share
6 answers

buffer is just a pointer with no size information. However, the malloc () procedure will contain the size of the allocation you allocated, so when you free () it will free up the required amount of space. Therefore, if you do not want to dive into the malloc () functions, I recommend that you simply save the distribution size yourself. (for a possible implementation, see an example in another API answer).

+3
source

For GNU glibc:

 SYNOPSIS #include <malloc.h> size_t malloc_usable_size (void *ptr); 

DESCRIPTION

The malloc_usable_size () function returns the number of bytes used in the block pointed to by ptr, the pointer to the memory block allocated by malloc (3), or the function associated with it.

+19
source

You cannot do such a test. You are responsible for remembering how much memory you have allocated. If the buffer was provided to you by someone else, ask them to transfer size information, and also make them responsible for transmitting the correct value or run the program.

+11
source

Since buffer is a pointer (not an array), the sizeof operator returns the size of the pointer, not the size of the buffer that it points to. There is no standard way to determine this size, so you need to keep accounting yourself (i.e. Remember how much you allocated.)

BTW, this is the same for

  char *p = "hello, world\n"; /* sizeof p is not 13. */ 

Interesting that

  sizeof "hello, world\n" 

equals 14. Can you guess why?

+6
source
 struct buffer { void *memory size_t length; }; void *buffer_allocate( struct buffer *b, size_t length ) { assert( b != NULL ); b->memory = malloc( length ) b->length = length; // TRD : NULL on malloc() fail return( b->memory ); } int buffer_valid( struct buffer *b, size_t length ) { assert( b != NULL ); if( b->memory == NULL or length > b->length ) return( 0 ); return( 1 ); } void *buffer_get( struct buffer *b ) { assert( b != NULL ); return( b->memory ); } 

Use the API, not malloc / free, and you won't go wrong.

0
source

sizeof is used to calculate size for real objects, not for pointers to objects in memory. It returns the size of structures or primitives. I mean this will work, but give you the size of the pointer, not the structure it points to. To get the length of any type of array, use:

STRLEN (buffer)

0
source

All Articles