2

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

Community
  • 1
  • 1
Moataz Elmasry
  • 2,509
  • 4
  • 27
  • 37

2 Answers2

6

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.

  • I didnt document myself enought, sorry about the misleading post. – tomahh Oct 05 '12 at 15:59
  • @TomAhh No problem, I'm not angry of you in any means - a bit more experience and you'll see that there is rarely an "impossible" thing in programming :) –  Oct 05 '12 at 16:00
  • @H2CO3 thanks looks like a very nice solution. you are using 1024 for size, is there a reason for that, or can it be any arbitary size for your functions to work? – Moataz Elmasry Oct 05 '12 at 16:08
  • 2
    @MoatazElmasry I'm using it because it's nice. –  Oct 05 '12 at 16:09
  • 1
    +1: Direct answer to the question, and directly notes the answer it is platform *dependent*. Marked as one of my favs. I wouldn't use it in production code, but for trace-debugging this is outstanding. Thanks. – WhozCraig Oct 22 '12 at 04:28
  • this wont work you need to convert the buffer to a char like: = (char*) malloc(1024); – theodore hogberg Dec 18 '21 at 20:02
2

malloc() doesn't really know about arrays or other things, it just allocates a block of memory for you. The size of this space isn't available to you unless you track it yourself separately. This is why most methods that act on arrays take two arguments, the array and the length.

Herms
  • 37,540
  • 12
  • 78
  • 101