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
The main issue with your code that are missing a {}
around your if block. Other minor issues:
main()
's signature should be int main(void)
or (int main(int, char **)
).void *
sizeof(char)
is defined as 1 so you don't really need the sizeof
#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;
}