When I use a char array as a container of binary data, each item in the array could be a 8-bit integer. How can I get char array length when the array is assigned to a char pointer? Here's an example:
// t.c
#include <stdio.h>
#include <string.h>
int main() {
char buffer[3] = {12, 13, -14};
char * p = buffer;
printf("%d ", sizeof(buffer));
printf("%d ", strlen(buffer));
printf("%d ", sizeof(p));
printf("%d ", strlen(p));
printf("%d\n", sizeof(char *));
return 0;
}
The ouput is: 3 6 8 6 8
gdb debugging:
(gdb) where
#0 main () at t.c:8
(gdb) p p
$1 = 0x7fffffffe4b0 "\f\r\362\377\377\177"
(gdb) p (char *)buffer
$2 = 0x7fffffffe4b0 "\f\r\362\377\377\177"
(gdb) x/8db 0x7fffffffe4b0
0x7fffffffe4b0: 12 13 -14 -1 -1 127 0 0
As you can see, strlen(buffer) is not the array length because follwing memory is not 0. sizeof(p) is not the array length since it's actually the size of a char pointer (64 bit OS).
My question is, when p is passed to another function, how do I get the real array length by p? Please note the char array in the example is not something like:
char buffer[4] = "abc";