Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First you should understand that <strong>sizeof</strong>(xxx) where xxx is any left value expression (a variable) is always equivalent to do <strong>sizeof</strong>(<em>type of xxx</em>). Hence what is really doing your <strong>sizeof</strong>(str) is returning the size of a char *, that is the size of any other pointer. On a 32 bits architecture you'll get 4, on a 64 bits architecture it'll be 8, etc.</p> <p>So, as others also explained you have to know the length of the string you want to allocate, and then add 1 to store the terminal \0, C implicitly use to put at the end of strings.</p> <p>But to do what you want (copy a string and allocate necessary space) it will be more simple and more efficient to use <strong>strdup</strong>, that does exactly that : a <strong>malloc</strong> and a <strong>strcopy</strong>.</p> <p>You should also not forget to free space you allocated yourself (using malloc, calloc, strdup or any other allocation function). In C it won't go away when allocated variable go out of scope. It will stay used until the end of the program. That's what you call a memory leak.</p> <pre><code>#include &lt;string.h&gt; /* for strdup, strlen */ #include &lt;stdio.h&gt; /* for printf */ int main() { char * str = "string"; char * copy = strdup(str); printf("bytes at least allocated for copy: %d\n", strlen(copy)+1); printf("%s\n", copy); free(copy); } </code></pre> <p>One last point : I changed message to <em>bytes at least allocated</em> because you don't really know the size allocated when calling malloc. It quite often allocates a slighly more space that what you asked for. One reason is that in many memory managers free blocks are linked together using some hidden data structure and any allocated block should be able to contain at least such structure, another is that allocated blocks are always aligned in such a way to be compatible with any type alignment.</p> <p>Hope it will help you to understand C a little better.</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