Note that there are some explanatory texts on larger screens.

plurals
  1. POSacrificing expression of intent for memory management
    text
    copied!<p>I'm pretty new at C programming, and this type of thing keeps popping up. As a simple example, suppose I have a <code>struct http_header</code> with some <code>char</code> pointers:</p> <pre><code>struct http_header { char* name; char* value; }; </code></pre> <p>I want to fill an <code>http_header</code> where <code>value</code> is the string representation of an int. I "feel" like, semantically, I should be able to write a function that takes in an empty header pointer, a name string, and an <code>int</code> and fills out the header appropriately. </p> <pre><code>void fill_header(struct http_header *h, char* name, int value) { h-&gt;name = name; char *value_str = malloc(100); sprintf(value_str, "%d", value); h-&gt;value = value_str; } int main(int argc, const char * argv[]) { struct http_header h; char *name = "Header Name"; int val = 42; fill_header(&amp;h, name, val); ... free(h.value); } </code></pre> <p>Here, the calling code reads exactly as my intent, but in this case I'm creating the <code>value</code> string dynamically, which means I'd have to free it later. That doesn't smell right to me; it seems like the caller then knows too much about the implementation of <code>fill_header</code>. And in actual implementations it may not be so easy to know what to free: consider filling an array of <code>http_header</code>s where only one of them needed to have its value <code>malloc</code>ed.</p> <p>To get around this, I'd have to create the string beforehand:</p> <pre><code>void fill_header2(struct http_header *h, char* name, char *value_str) { h-&gt;name = name; h-&gt;value = value_str; } int main(int argc, const char * argv[]) { struct http_header h; char *name = "Header Name"; int value = 42; char value_str[100]; sprintf(value_str, "%d", value); fill_header2(&amp;h, name, value_str); } </code></pre> <p>As this pattern continues down the chain of structures with pointers to other structures, I end up doing so much work in top level functions the lower level ones seem hardly worth it. Furthermore, I've essentially sacrificed the "fill a header with an <code>int</code>" idea which I set out to write in the first place. I'm I missing something here? Is there some pattern or design choice that will make my life easier <em>and</em> keep my function calls expressing my intent?</p> <p>P.S. Thanks to all at Stackoverfow for being the best professor I've ever had. </p>
 

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