Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

const misunderstanding in coding standards doc #1002

Open
Util opened this Issue Oct 5, 2013 · 1 comment

Comments

Projects
None yet
2 participants
Owner

Util commented Oct 5, 2013

Reported by: zefram@fysh.org

docs/pdds/pdd07_codingstd.pod has a section about using const qualification with pointers, with an example concerned with strlen. It says that in the code:

char *p;
int n = strlen(p);

, the fact that strlen's parameter is typed "const char *" is what lets the compiler diagnose use of an uninintialised value. This is incorrect. In the code fragment given, p has not been initialised, so using it as the argument to any function is use of an uninitialised value, regardless of the declared types of p or the function parameter. (C passes by value, not by reference.) The nearby situation where const qualification is relevant is:

char c;
int n = strlen(&c);
char d = c;

In this case, c might be used uninitialised when being copied to d. The compiler might consider whether strlen might initialise c through its pointer parameter. The const qualification means that it cannot, and therefore c is indeed used uninitialised when being copied to d. (In fact, c is used uninitialised earlier, inside strlen, but the compiler can't determine that without specific knowledge of strlen's behaviour.)

But all of that is a rather dubious motivation for using const. A better one is that it catches mistakes involving modifying an object that, by API contract, the code isn't permitted to.

-zefram

Contributor

gerdr commented Oct 5, 2013

I won't comment on the original issue, but the bug report contains another inaccuarcy:

The compiler might consider whether strlen might initialise c through its pointer parameter. The const qualification means that it cannot, and therefore c is indeed used uninitialised when being copied to d.

This is actually not guaranteed by C language semantics - casting const away to initialize the value is perfectly fine and will only result in undefined behaviour if the memory location itself were declared const, ie

const char c;

If the compiler can't see the body of strlen(), it may not optimize on the assumption that the object will not be modified just because the pointer argument was const-qualified.

Even adding restrict does not help - while a restrict-qualified pointer-to-const does indeed guarantee immutability callee-side, calling code may not rely on this as restrict semantics only apply if the argument is actually accessed, which the caller cannot know without inspecting the function body.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment