-1

I create a buffer like this but I don't give it content. Then I try to view strlen() of this block memory.

    int size = 24;
    char *c;
    c = (char *)malloc(size);
    printf("%d\n", strlen(c));

What I get is not 24 but 40. I try to view the value from c[40] to c[47] and I always get \0 but after c[47] is not null anymore. When I set size = 18, the result isn't 40 anymore. It's 32. And values from c[32] to c[47] are all \0. When I set size = 7, the result is 24 and values form c[24] to c[47] are all \0.
I know using strlen for an array like this is not able to give me the size I used in malloc() function. I just wonder why this happened and when we change the value of size, how the result change? Is there anything we can deal with using this?
Edit: It seem like everyone think the result is unpredictable. It's the fact that it's always a multiple of 8 and when we increase the size, there is a limit where the result increase. We can determine exactly the value of size that make the result change and it doesn't change despite how many times we test. Does it depend on OS not just C language or compiler? Why 8 is chosen?

P.A
  • 741
  • 4
  • 16
Huy Ha
  • 120
  • 10

2 Answers2

2

You should read the documentation, strlen() is for the length of strings. Without much detail I will tell you one thing,

There is no way to get the length of a pointer dynamically, so your only option is to store it and use it later.

A simple elegant method, is to use a struct for that, where you store the size and use it every time you need.

struct pointer_type {
    void *pointer;
    size_t allocated_size;
};

As for the "What i get is not 24 but 40" question,

Your pointer, is uninitialized. This causes what is known as undefined behavior because the way strlen() works is by dereferencing the pointer and counting characters until a given character occurs, something like

int strlen(const char *const str)
{
    int count = 0;
    while (*(str++) != '\0') ++count;
    return count;
}

and since your pointer points to random garbage, this will not work right and the returned value is unpredictable.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Thank for your answer. I know about strlen() function and i don't want to get the size. Actually, the real question is how value of bytes from pointer to pointer + x is set like that especially where the null value appear first time. – Huy Ha Mar 09 '17 at 11:38
  • All your tests are unreliable because of **UNDEFINED BEHAVIOR**, so you can't try to predict anything at all. – Iharob Al Asimi Mar 09 '17 at 11:39
2

The memory you allocated isn't initialized. Passing it to strlen, a function that expects a NUL terminated string, has undefined behavior. So you can get whatever, you don't even have to get any result.

There is not built-in way in C to know the exact size of an allocated block of memory.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458