C error printing string from array of strings

I am new a C an I am trying to get strings for array and I can't print them for some reason someone knows why?. Thank you

int main(void)
{

    int number_friends = 0, i = 0;
    printf("Enter number of friends: ");
    scanf("%d", &number_friends);
    getchar();
    char** friends = (char**)malloc(number_friends * sizeof(char*));
    get_friends_names(friends, number_friends);
    for (i = 0; i < number_friends; i++)
    {
        printf("%s\n", friends[i]);
    }
    free(friends);
    getchar();
    return 0;
}

void get_friends_names(char** friends, int size)
{
    char name[STR_LEN] = {0};
    int i = 0, len = 0;
    for (i = 0; i < size; i++)
    {
        fgets(name, STR_LEN, stdin);
        name[strcspn(name, "\n")] = 0;
        friends[i] = malloc(STR_LEN);
        friends[i] = name;
    }
}

1 answer

  • answered 2021-05-03 17:54 Vlad from Moscow

    This code snippet

        friends[i] = malloc(STR_LEN);
        friends[i] = name;
    

    does not make a sense and has two drawbacks.

    The first one is that there is a memory leak. That is a memory was allocated dynamically and its address was assigned to the pointer friends[i] And then the pointer was at once reassigned.

    The second one is that you assigned to the pointer friends[i] the address of a local array that will not be alive after exiting the function.

    You need to write at least like

    friends[i] = malloc(STR_LEN);
    strcpy( friends[i], name ); 
    

    or

    friends[i] = malloc( strlen( name ) + 1 );
    strcpy( friends[i], name ); 
    

    Also in main you need to free all the allocated memory like

    for (i = 0; i < number_friends; i++)
    {
        free( friends[i] );
    }
    free(friends);
    

    Pay attention to that the variable len is not used within the function.