length of char pointer c++

c

Solution

SomeRandomGuyOnSO:

No it's not.

Me:

Yes, it is, but it's gonna be non-standard and platform dependent.

Apart from that, let me not repeat all the good advice about using standard C++ containers; let me actually answer your question instead. Doing a quick Google search on the topic brings up methods for doing this. Examples:

// OS X
#include <malloc/malloc.h>

char *buf = malloc(1024);
size_t howManyBytes = malloc_size(buf);
printf("Allocated %u bytes\n", (unsigned)howManyBytes);

// Linux
#include <malloc.h>

char *buf = malloc(1024);
size_t howManyBytes = malloc_usable_size(buf);
printf("Allocated %u bytes\n", (unsigned)howManyBytes);

// Windows, using CRT

char *buf = malloc(1024);
size_t howManyBytes = _msize(buf);
printf("Allocated %u bytes\n", (unsigned)howManyBytes);

All three snippets are supposed to print 1024 or greater.

Problem

Possible Duplicate: How to find the sizeof(a pointer pointing to an array) When declaring a char pointer using malloc for example. is there a way to determine the allocated length. Example, if I define a char array, I can easily find the number of elements ``` char a[10]; a[0]='c'; cout << sizeof(a) / sizeof(a[0]); ``` which would yield 10. on the other hand if I tried with a char pointer ``` char *a; a = (char*)malloc(10); a[0] = 'c'; cout << sizeof(a) / sizeof(a[0]); ``` then it yields 8, which is obviously the size of the pointer, not the allocated length. is it possible to find the allocated length of a char pointer? The reason I'm asking this and not use std::string or other, is because I came upon this question while cracking some interview question. so its out of curiousity

Original source

Related problems