-1

I am very new to programming with C but I have spent a few semesters in C++. I have a homework assignment that I just started and I ran into an issue within the first few lines of code I have written and I am not sure what is going on. It will compile fine and when I run it I am able to enter in a string but once I hit enter I get the segmentation fault (core dumped) error message. Here is my code. I just started and I will be adding a lot more to it and will also be implementing functions in my program as well but I am taking it in baby steps:

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

struct profile {
    char *f_Name;
    char *l_Name;
    int age;
    char *email;
    char *password;
};

int main(void)
{
    struct profile userOne; //creates a variable
    printf("Please enter your first name: \n");
    fgets(userOne.f_Name, sizeof(userOne.f_Name), stdin);
    //takes input from user.
    //I want to use fgets because my professor wants us to consider  
    //bufferoverflows
    printf("%s\n", userOne.f_Name); //prints it to the screen
    return 0;
}
kakkarot
  • 478
  • 1
  • 9
  • 24
Ch0wder
  • 3
  • 2
  • What did you find when you ran it in a debugger or added some prints to track how far it is getting? (hint: are you sure all your pointers are pointing to memory you're allowed to access?) – John3136 Oct 12 '15 at 03:53
  • Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](http://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – CodeMouse92 Oct 12 '15 at 15:27

2 Answers2

1

You just declared a pointer variable without allocating memory to it. Use the malloc function first to allocate memory and then get the value from stdin.

userOne.f_Name = (char *) malloc( n * sizeof(char));

where n is the number of characters in your string

http://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm

The following link has info on Segmentation fault

What is a segmentation fault?

Community
  • 1
  • 1
kakkarot
  • 478
  • 1
  • 9
  • 24
  • thank you for the fast reply! I tried to implement your code right before my fgets statement but it would only print out the first three letters of the string and not the whole f_Name entered. – Ch0wder Oct 12 '15 at 14:51
  • @Ch0wder Well. That depends on the value of n. What value did you assign to n. – kakkarot Oct 13 '15 at 03:22
  • I tried a few different values. started with 10 then 50 and finally tried a larger number 5000 or so. – Ch0wder Oct 15 '15 at 06:00
1

You need to malloc (explicitly or via strdup) but sizeof(f_Name) in fgets is wrong--it's 4/8 because f_Name is a pointer, not a buffer. Try this:

char buf[5000];

fgets(buf,sizeof(buf),stdin);
userone.f_Name = strdup(buf);
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • thank you for that fast reply aswell! I was able to get it working with your method thank you very much. – Ch0wder Oct 12 '15 at 14:49