Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is strlen on a string with uninitialized values undefined behavior?

Tags:

c

string

strlen

strlen returns the number of characters that precede the terminating null character. An implementation of strlen might look like this:

size_t strlen(const char * str)
{
    const char *s;
    for (s = str; *s; ++s) {}
    return(s - str);
}

This particular implementation dereferences s, where s may contain indeterminate values. It's equivalent to this:

int a;
int* p = &a;
*p;

So for example if one were to do this (which causes strlen to give an incorrect output):

char buffer[10];
buffer[9] = '\0';
strlen(buffer); 

Is it undefined behavior?

like image 501
ペニス Avatar asked Sep 12 '14 01:09

ペニス


1 Answers

Calling the standard function strlen causes undefined behaviour. DR 451 clarifies this:

library functions will exhibit undefined behavior when used on indeterminate values

For a more in-depth discussion see this thread.

like image 162
M.M Avatar answered Oct 08 '22 00:10

M.M