Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to disable integer assignment (0) to an opaque variable?
    primarykey
    data
    text
    <p>I have a module whose implementation I want to hide from its clients.</p> <p>I chose to declare an opaque type which is actually a pointer to structure to be defined only in the implementation.</p> <p>It all is working fine, except that I can assign the zero value to a variable of this type, which I want to avoid.</p> <p>Here's an example in C.</p> <p>header file foo.h</p> <pre><code>/* foo.h */ typedef struct foo *foo_t; /* &lt;- sorry this was obviously flawed, the '*' was missing */ extern void foo_create( foo_t *t ); extern void foo_destroy( foo_t *t ); extern void foo_tile( foo_t x ); </code></pre> <p>implementation file foo.c</p> <pre><code>/* foo.c */ #include &lt;stdlib.h&gt; #include "foo.h" struct foo { int some_member; }; void foo_create( foo_t *t ) { if ( *t==0 ) { *t = malloc( sizeof(struct foo) ); } } void foo_destroy( foo_t *t ) { if ( *t!=0 ) { free(*t); *t = 0; } } void foo_tile( foo_t t ) { t-&gt;some_member++; } </code></pre> <p>And now here is an example client that uses the module: bar.c:</p> <pre><code>#include "foo.h" int main( int argc , char **argv ) { foo_t toe; foo_create( &amp;toe ); toe = 0; /* &lt;-- How to make the compiler (gcc) refuse this? */ toe = 1; /* &lt;--- the compiler rejects this YAY!! */ } </code></pre> <p>The opaque type is actually a pointer to a dynamically allocated structure; If I assign the value 0 to it I incur a memory leak which could be avoided If the compiler denied the assignment of 0 to this opaque pointer.</p> <p>Assigning non-null values to the pointer isn't accepted by the compiler, so I supose that with a little more effort the same could be achieved for zero value.</p> <p>Is it possible to disable this assignment? How can I achieve that? If using some bit of C++ or gcc specific constructs is needed, I'll be ok with that, although a pure C solution would be nice.</p> <p>Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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