0

I built a function that gets a string input from the user. Then it allocates memory, but after 3 inputs the program crashes.

void friendNamesInput(int friendNum, char **ppFriendName) {
    char name[50] = { 0 }; //name 
    char *byteReALL = 0; //allocate bytes
    int i = 0;
    for (i = 0; i < friendNum; i++)
    {
        printf("Enter name of friend %d:", i + 1);
        fgets(name, 50, stdin); //input 50
        byteReALL = (char*)malloc(sizeof(char)*strlen(name)); //allcate nedded mem
        strncpy(byteReALL, name,50); //copy string data
        ppFriendName[i] = byteReALL; //address to array of arrays

    }
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
user6721998
  • 3
  • 1
  • 5
  • Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane May 03 '18 at 19:49

1 Answers1

1

You're not allocating enough memory for the string you're copying:

byteReALL = (char*)malloc(sizeof(char)*strlen(name));

A string in C is null terminated, so you need to add 1 extra byte for that character. Also, sizeof(char) is defined to be 1, so no need to multiply:

byteReALL = malloc(strlen(name) + 1);

A better way to do this is to use strdup, which allocates space for a string and copies it to the newly allocated buffer in one step:

printf("Enter name of friend %d:", i + 1);
fgets(name, 50, stdin);
ppFriendName[i] = strdup(name);
dbush
  • 205,898
  • 23
  • 218
  • 273