Note that there are some explanatory texts on larger screens.

plurals
  1. POConst-correctness and immutable allocated objects
    primarykey
    data
    text
    <p>During a recent discussion (see comments to <a href="https://stackoverflow.com/questions/3965279/opaque-c-structs-how-should-they-be-declared/3965308#3965308">this answer</a>), R.. recommended to never create aliases for pointer-to-<code>const</code> types as you won't be able to deallocate the referenced objects easily in a conforming C program (remember: <code>free()</code> takes a non-<code>const</code> pointer argument <del>and C99 6.3.2.3 only allows conversions from non-qualified to qualified</del>).</p> <p>The C language obviously assumes the existance of an owner for any allocated object, ie someone somewhere has to store a non-<code>const</code> pointer to the object, and this someone is responsible for deallocation.</p> <p>Now, consider a library allocating and initializing objects which are non-modifyable from user-space code, so function calls always return <code>const</code>-qualified pointers.</p> <p>Clearly, the library is the owner of the object and should retain a non-<code>const</code> pointer, which is somewhat silly as the user already supplies a perfectly valid, but <code>const</code> copy of the pointer on each library call.</p> <p>To deallocate such an object, the library has to discard the <code>const</code> qualifier; as far as I can tell, the following</p> <pre><code>void dealloc_foo(const struct foo *foo) { free((void *)foo); } </code></pre> <p>is valid C; it would only be invalid if the <code>foo</code> parameter were additionally <code>restrict</code>-qualified.</p> <p>However, casting away <code>const</code> seems somewhat hack-ish.</p> <p>Is there another way aside from dropping the <code>const</code> from all return values of library functions, which would lose any information about object mutability?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload