how to prevent a segfault in C (when taking an argument of the wrong type)
<p>I have two files, User.h and test.c:</p>

<p>User.h</p>

<pre><code>include &lt;stdio.h&gt;                                                              
#include &lt;string.h&gt;                                                             

struct User {                                                                 
    char name[21];                                                              
};                                                                              

struct User newUser(char* name) {                                           
    struct User newUser;                                                    
    memset(newUser.name, '\0', 21); // ensure string ends with '\0'           
    memcpy(newUser.name, name, 20); // copy first 20 chars of string          
    return newUser;                                                           
} 
</code></pre>

<p>test.c</p>

<pre><code>#include "User.h"                                                             

int main() {                                                                    
    struct User testUser = newUser(34);                                           
    printf("name is: %s\n", testUser.name);                                           
    return 0;                                                                   
} 
</code></pre>

<p>I am intentionally passing the wrong type of argument to  a function, but trying to avoid a segfault:</p>

<p>If I were to pass a string of any length to newUser(), this function would take up to 20 characters of it and store it in .name without a segfault because it is guaranteed to end with a null byte. </p>

<p>Here I am passing an int instead. Because it is expecting a string, I get a compiler warning, but it compiles anyway.  When run, I get a segmentation fault.</p>

<p>I suppose the segmentation fault occurs when the function reads past the name[21] array, but if it's guaranteed to have a null byte, why does it continue to read past it?  It's expecting a string, shouldn't it treat any argument like a string and terminate at '\0'?  </p>

<p>It seems my logic is flawed, can someone educate me about what's really going on here? </p>