Originally Posted by
username1
Why does the first program work without malloc, but the second one doesn't unless I use malloc?
To make your second program work without malloc, you can write it like this:
Code:
int main(){
char word[6];
strcpy(word, "abcde");
printf("You entered: %s\n", word );
}
The 6 means that 6 bytes are allocated at compile time, which is enough to hold strings which have a strlen of 5 or less.
Quite often, the number 6 (N) is known, but you don't know how big the strings will be. Then it's better to use strncpy to avoid undefined behavior.
Code:
#define WORD argv[1]
#define N 6
int main(int argc, char *argv[]){
if (argc != 2) {
printf("Usage: printword WORD\n");
exit(EXIT_SUCCESS);
}
char word[N];
if (strncpy(word, WORD, N)[N-1] != '\0') {
printf("Sorry, that word is too long. Program will abort.\n");
exit(EXIT_FAILURE);
}
printf("You entered: %s\n", word);
exit(EXIT_SUCCESS);
}
With strncpy, the character at position N-1 is guaranteed to be '\0' if the string "fits". Therefore, if it is not '\0' you know that it was too big.