-1

I encountered this issue while testing around printf.

This code outputs 5, which is what I want.

#include <stdio.h>

size_t  ft_strlen(const char *str)
{
    size_t  i;

    while (*str++)
        i++;
    return (i);
}

int main(void)
{
    printf("%zu\n", ft_strlen("Hello"));
    return (0);
}

But, when I declare a char *str; above my printf, the output shows 4294967301

Why is the printf affected by the above declaration ?

LeSauvage
  • 94
  • 7
  • 6
    Function `ft_strlen()` fails to initialize its local variable `i`. – John Bollinger Jul 14 '21 at 19:41
  • Added `i = 0` and solved it.. Thanks. – LeSauvage Jul 14 '21 at 19:47
  • Note, while the counter approach to `strlen()` works fine for short strings, it become much less efficient than the library implementation for longer strings. (the library version typically checks 4-bytes at a time for `\0`) – David C. Rankin Jul 14 '21 at 19:57
  • Thanks for the info @DavidC.Rankin, but I have to use my own ft_strlen() for my school assignment. I'll sure take a look at strlen() later! – LeSauvage Jul 14 '21 at 20:04
  • Absolutely nothing wrong with that. Just making you aware when you work with long strings (1000+ characters) you will see a sizeable difference in efficiency, and by the time you get to 1000000 character strings you will see orders of magnitude difference in execution time. – David C. Rankin Jul 14 '21 at 20:08

1 Answers1

1

Initialising int i to 0 resolved my issue.

size_t  ft_strlen(const char *str)
{
    size_t  i;

    i = 0;
    while (*str++)
        i++;
    return (i);
}
LeSauvage
  • 94
  • 7