Home > OS >  How do I read input with scanf_s(), and then assign the data to your newly allocated memory?
How do I read input with scanf_s(), and then assign the data to your newly allocated memory?

Time:09-05

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:

  1. main()'s signature should be int main(void) or (int main(int, char **)).
  2. don't cast void *
  3. sizeof(char) is defined as 1 so you don't really need the sizeof
  4. use a define intead of magic values
  5. scanf_s is a microsoft extension so I can't test it for you but I think you want to include the size
  6. 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
  7. 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
  8. 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;
}
  • Related