Originally Posted by
sahtopi
Does anyone see problems with this?
Yes:
- You forgot to check the return value of malloc: malloc could return a null pointer.
- You forgot to specify a field width for "%s" with scanf: without the field width, it is vulnerable to buffer overflow, i.e., the user could input MAXPLAYERNAME or more non-whitespace characters and they will all be stored in the dynamic array, even though there is only space for a string of length MAXPLAYERNAME - 1 at most.
- You forgot to check the return value of scanf: if scanf does not return 1 (as there is one assignment to be made), perhaps you should free the memory allocated and return a null pointer to indicate the input error.
Note that sizeof(char) is always equal to 1, so I suggest either:
Code:
char *PlayerName = malloc(sizeof(PlayerName[0]) * MAXPLAYERNAME);
or:
Code:
char *PlayerName = malloc(MAXPLAYERNAME);
Also, it is better to be explicit about an empty parameter list, i.e., this:
Code:
char* getPlayerName()
should be:
Code:
char* getPlayerName(void)
Other possible problems may involve things like whether you included <stdlib.h> and <stdio.h>, and whether you defined MAXPLAYERNAME correctly, but we cannot check these.