-1

I am attempting to do this problem from CS50 without using the training wheels. bc somehow I can only access the regular version of VS code instead of the one that has the cs50 library. See my code below.

After I execute the code, it will prompt for both of the user inputs but it won't print them. It says segmentation fault.

Thank you.

#include <stdio.h>
#include <string.h>

typedef struct
{
    char *name;
    int vote;
} 
candidate;

candidate get_candidate(char *prompt);

int main(void)
{
    candidate president = get_candidate("Enter candidate: ");
    printf("%s\n", president.name);
    printf("%i\n", president.vote);                                

}

candidate get_candidate(char *prompt)
{
    printf("%s\n", prompt);


    candidate c;
    printf("Enter a name:");
    scanf("%s", c.name);


    printf("Enter votes:");
    scanf("%i", &c.vote);

    return c;                   //go back to main 
}
Linnifer
  • 11
  • 2

1 Answers1

1

The name member of the candidate struct isn't being properly allocated before the scanf.

Try allocating memory using malloc before scanf: c.name = (char *)malloc(100 * sizeof(char));

Edit: As mentioned in a comment, a simpler alternative would also to just go char[100], which should work out fine unless you have a 100+ character testcase.

xingharvey
  • 131
  • 6
  • In C++ the cast on `malloc` is necessary, though its use should raise questions outside of very niche requirements. In C it is unnecessary. [Further reading.](https://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc) – Chris Jun 15 '23 at 21:23
  • Thank you. Just trying to understand, why in this case I cannot use char *? But it works if I'm just trying to store a string in a variable? – Linnifer Jun 15 '23 at 21:39
  • What is a `char *`? It's a pointer to a `char` in memory. Which `char`? Well, that's the rub. Unitialized, it doesn't point to any `char` in memory. – Chris Jun 16 '23 at 00:06
  • @Linnifer With `scanf("%s", c.name);`, `scanf()` receives a pointer `c.name`. The value of that pointer is where `scanf()` will store user input as a _string_. As code does not first initialize nor assigned that pointer, `scanf();` receives an invalid location to store user input. – chux - Reinstate Monica Jun 16 '23 at 07:03