Size of a dynamic array

0

I'm doing dynamic memory allocation testing, but when I try to get the size of the array I always have the same result.

int main()
{
    int *teste=malloc(sizeof(int) * 10);
    int len=sizeof(teste) / sizeof(int);

    print("%i\n", len);
    return 0;
}

Compiling with gcc:

bash-4.2$ ./teste
2

It does not matter if I put sizeof(int) * 100 or 10 , it always returns 2 :( What am I doing wrong?

    
asked by anonymous 06.10.2017 / 21:51

2 answers

1

The idiomatic sizeof(teste) / sizeof(int) is only able to calculate the in bytes size of statically allocated buffers:

int teste[ 123 ];
printf("%d\n", sizeof(teste) / sizeof(int) ); /* 492 / 4 = 123 */

In your case, teste is a pointer to a dynamically allocated memory region and sizeof(teste) is the size in bytes that that pointer occupies, not the size of the memory it is pointing to.

int * teste = NULL;
printf("%d\n", sizeof(teste) / sizeof(int) ); /* 8 / 4 = 2 */

What about:

int main()
{
    int len = sizeof(int) * 10;
    int *teste=malloc(len);

    print("%d\n", len); /* 40 */

    free(teste);
    return 0;
}
    
06.10.2017 / 23:17
0

Thanks for the collaborations, in your example Lacobus in my project it would not work because I do not know the size of the array when creating and I always reallocate but I remembered something that can be done there of the data structure classes.

I made a structure

struct __buf {
   int *ptr;
   int len;
};

As I adjust the size of the array I update the structure, like this:

__buf buffer_serial;
...
buffer_serial.ptr = malloc ( sizeof(int) * len);
buffer_seria.len = len;
...
    
07.10.2017 / 04:34