what am I doing wrong
Others have already pointed out some of the errors, but nobody has shown the right solution yet.
Your code is inherently vulnerable to buffer overflows. The gets()
function doesn't let you specify the buffer size, so if you enter more than 256 characters, this will write out of the bounds of your array. That's bad.
What you should do instead is
- not use a separate function for this (because it has no benefits in this particular case), and
- call
fgets()
on your array:
#include <stdio.h>
int main()
{
char name[256];
fgets(name, sizeof name, stdin);
printf("Name = %s\n", name);
return 0;
}
Also, if you ever consider dynamic memory allocation:
Do not cast. It's a deadly sin.
Check the return value of malloc()
.
You will still want to keep track of the buffer size; how about a function like this?
#define NAME_LENGTH 256
char *getName(void)
{
char *buf = malloc(NAME_LENGTH);
if (buf == NULL) {
return NULL;
}
fgets(buf, NAME_LENGTH, stdin);
return buf;
}
But, as I mentioned in the comments, in this case you don't need dynamic memory allocation at all.