I have two files, User.h and test.c:
User.h
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;
}
test.c
#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?