7

I am new to programming in general and to C in particular. I am trying to write a program that uses an array of structs, but I am experiencing problems if that struct contains strings. Somehow the compiler crashes after the user has given the last input.

The struct below is just a simplified version containing only one item, because the problem seems to be reading strings into the array. Any help is much appreciated, thanks in advance.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
    char* name;
}student;

int main()
{
    int size;
    printf("enter number of entries\n");
    scanf("%d" , &size);
    student* all=malloc(size*sizeof(student));

    int i;
    for(i=0;i<size;i++)
    {
        printf("enter name\n");
        scanf("%s" , all[i].name);
    }

    return 0;
}
8
  • 2
    Don't forget to free that memory Commented Jan 8, 2016 at 13:47
  • and don't produce any other bugs while you'll be adding this Commented Jan 8, 2016 at 13:52
  • change also int size to long unsigned int or size_t. Commented Jan 8, 2016 at 13:53
  • 2
    Very good that you include a minimal version of your problem and not your original code!!! That makes this a much better question than just dumping whatever you have on us. Remember to do the same for future questions. Commented Jan 8, 2016 at 14:02
  • 1
    We still badly need a canonical duplicate for "program crashes when I try to dump stuff into the address of an uninitialized pointer" :( Commented Jan 8, 2016 at 14:26

2 Answers 2

6

Before taking input scanf("%s" , all[i].name); , you need to allocate memory to all[i].name .

An example-

for(i=0;i<size;i++)
{
    all[i].name=malloc(20*sizeof(*(all[i].name)));
    if(all[i].name!=NULL){
       printf("enter name\n");
       scanf("%19s" , all[i].name);
    }
}
//use these strings
for(i=0;i<size;i++){
       free(all[i].name);                  //free the allocated memory 
}
free(all);

Or in your structure instead of char * ,declare name as a char array (if you don't want to use dynamic allocation)-

typedef struct{
  char name[20];                     //give any desired size
 }student;
/*           no need to free in this case   */
Sign up to request clarification or add additional context in comments.

1 Comment

@iharob Mentioned that .
0

No memory is allocated for the students names (char* name), so when trying to scanf to that pointer, invalid memory is accessed and the program crashes.

The easiest way is to declare name as an array: char name[28];

The return value of malloc() needs to be checked too, in case there was problem allocating the memory for the students, which would return a NULL pointer. At the end, the allocated memory needs to be freed with free().

For example:

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

typedef struct {
    char name[28];
    unsigned int age;
} student;

int main()
{
    size_t size = 0;
    printf("\nEnter number of entries: ");
    scanf("%zu", &size);
    // add some check for size

    student* students = (student*)malloc(size * sizeof(student));

    if (students == NULL) {
        printf("\nProblem with allocating memory:\n"
               " - size: %zu\n"
               " - total size needed: %zu\n",
               size, size * sizeof(student));
        return 0;
    }

    for (size_t i = 0; i < size; ++i) {
        printf("Enter name: ");
        scanf("%27s", students[i].name);
        printf(" Enter age: ");
        scanf("%u", &students[i].age);
    }

    printf("\nList of students:\n");

    for (size_t i = 0; i < size; ++i) {
        printf("%s (%u)\n", students[i].name, students[i].age);
    }

    free(students); // free the allocated memory

    return 0;
}

3 Comments

Don't forget to clear the input buffer after using scanf: while(getchar() != '\n');
I edited your answer: the format specifiers for scanf were also wrong.
@d3l - Thanks, I updated the format specifiers (although "%zu" might not be supported on all (older) compilers). I don't think clearing \n is needed here since we're not scanning for chars.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.