ridthyself ridthyself - 1 year ago 45
C Question

how to prevent a segfault in C (when taking an argument of the wrong type)

I have two files, User.h and test.c:


include <stdio.h>
#include <string.h>

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;


#include "User.h"

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

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

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.

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.

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'?

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

Answer Source

I am intentionally passing the wrong type of argument to a function, but trying to avoid a segfault.

That is same as saying I'm going into the sea but trying to avoid getting wet.

When you do something illegal, all you can end up with is invoking undefined behavior which may lead to segfault.

The best way to avoid it is to write correct code.

The problem is, the function expects a char* and you're passing an int. That's not allowed, anyway. It's wrong, and you must not ignore compiler warnings.

To elaborate, the function expects a pointer-to-char (char*) type and further, the code involves reading from the address location pointed by the pointer. As you're passing an int to the function (ignoring compiler warnings), the code tries to access the memory pointed by the supplied integer value, which is very likely an invalid memory location. So, this attempt to access invalid memory location invokes the UB.