0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char* buffer = malloc(1000*sizeof(char));
    memset(buffer,'\0',1000);

    printf("%ld\n",sizeof buffer);    // Size of Pointer
    printf("%ld\n",sizeof *buffer);   // Size of Memory Block pointed at by buffer
    printf("%ld\n",strlen(buffer));   // Length of String
    return 0;
}


//  Output:-
//  8
//  1
//  0

The code works fine.

The output is as expected, but how do I find the length of contiguous memory that I initialized with malloc if I don't know the length?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
asds_asds
  • 990
  • 1
  • 10
  • 19

1 Answers1

4

There's no standard way to find out how large a block of malloc'ed memory is.

It's up to you to keep track of the size yourself.

dbush
  • 205,898
  • 23
  • 218
  • 273