I'm trying to assign user input to a chunk of memory I have allocated to then print it on screen but the program just crashes after the input is made
#include <stdio.h>
#include <stdlib.h>
main() {
char *movie;
movie = (char*)malloc(80 * sizeof(char));
if (movie != NULL)
printf("Enter favorite movie: ");
scanf_s("%s",movie);
printf("You entered : %s", movie);
system("pause");
}
The program works if I use something like gets() but I specifically need to use scanf_s() and this is where the problem happens I'm using VS2019
CodePudding user response:
The main issue with your code that are missing a {}
around your if block. Other minor issues:
main()
's signature should beint main(void)
or (int main(int, char **)
).- don't cast
void *
sizeof(char)
is defined as 1 so you don't really need thesizeof
- use a define intead of magic values
- scanf_s is a microsoft extension so I can't test it for you but I think you want to include the size
- use getchar() / getc(stdin) instead of a system("pause") which relies on the operating system (in this case dos/windows) for no particular good reason
- free allocated memory is good practice even if the operating system does it for you. This will make memory leak checkers happy if ever use one
- return an exit code
#include <stdio.h>
#include <stdlib.h>
#define LEN 79
#define stringify(s) stringify2(s)
#define stringify2(s) #s
int main(void) {
char *movie = malloc(LEN 1);
if (movie) {
printf("Enter favorite movie: ");
scanf_s("%" stringify(LEN) "s", movie, LEN 1);
printf("You entered : %s\n", movie);
}
getchar();
free(movie);
return 0;
}