Q:

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?

A:

Your while loop should not be comparing against '0'.
'0' (ascii) is value 48!
Strings don't end with 48.
Strings end with 0.
You should be doing:
while(length[string] != 0)

(and all the other answers and comments about other problems in your code are also accurate)

A:

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.

A:

It crashes because I'm guessing the pointer wasn't assigned to any dynamically-allocated object (object created with malloc). Just because it's a pointer does not guarantee the fact that it was assigned to something allocated with malloc and therefore must be freed. Pointers can point to objects (not necessarily dynamically-allocated ones) and in this case I'm assuming the pointer is set to a string literal ("Hello World"). The pointer and its point-ee are allocated on the stack and need not be deleted. free is unnecessary in this case because they both will be destructed at the end of their respective scopes. Moreover, anything you create with malloc must be deleted/freed or you risk a memory leak. And otherwise freeing a pointer not assigned to something made with malloc causes undefined behavior which may include a crash.

