I'm using WSL Ubuntu-20.04 LTS and compiling with gcc.
I'm preparing some examples to teach the basics of C to CS Students and as I was reading about designated Initialisers, the following bit of code caused errors,
typedef enum {male, female} sexe;
struct human_t {
char * name;
char * title;
sexe gender;
};
struct human_t steve = {.name = "Steve",
.title = "Mr.",
.gender = male
};
strcpy(steve.name, "AA");
And reading the manual on strcpy the destination buffer being of larger size than "AA" I'm simply at a loss as to why this doesn't work.
I also observed the following :
struct human_t steve = {.name = "Steve",
.title = "Mr.",
.gender = male
};
char * new_name = "Gobeldydukeryboo";
realloc(steve.name, strlen(new_name));
strcpy(steve.name, new_name);
And this returns the error realloc(): invalid pointer.
Reading the manual on realloc the pointer must have been returned by a malloc call for it to work.
I'm having a feeling that designated initialisation does not call malloc, which would explain why realloc fails, it doesn't, however, explain why strcpy fails.
What's going on here ?