Search code examples
ccrashstrlen

Why does my strlen function keep "crashing"?


I'm trying to write a strlen function in C but it doesn't work.

int strlen(char*string)
{
    int length=0;
    while(length[string]!='0')
    {
        ++length;
    }
    free(string);
    return length;
}

It keeps on crashing no matter how many times I run the compiler. Whats wrong with my code?


Solution

  • You're probably freeing memory the function doesn't own.

    For example:

    strlen("42");
    

    would crash because "42" is a string literal - you can't modify it.

    Note that '0' is not the terminating character for a string, but the actual '0' character. Use either '\0' or 0.

    Remove the free and it should work.

    I'd also go with the more idiomatic string[length], which, beware, is illegal if string == NULL - so a null check is in order there.