Mihika Naik
Mihika Naik

Reputation: 11

Why am I getting a Segmentation error?

#include<stdio.h>
#include<string.h>
void main()
{
int entry,i;
printf("\nPlease indicate the number of records you want to enter :\n");
scanf("%d",entry);
char ent[entry][100000];
printf("\nPlease input records of students (enter a new line after each record), with following format first name last name score \n");
for(i=0;i<entry;i++)
    {
    gets(ent[i]);
    printf("%s",ent[i]);
    }
}

The following is a code to accept data of student , first name last name and then score.

Upvotes: 1

Views: 72

Answers (4)

autistic
autistic

Reputation: 15642

main should return int, not void.

int main(void) {
    /* ... */
}

scanf("%d",entry);

scanf expects the argument corresponding to the "%d" format specifier to be an int *. Your argument, however, is an int. Perhaps you meant this:

scanf("%d",&entry);

On that note, you should really check the return value of scanf. For all you know, the user didn't enter anything numeric.

if (scanf("%d", &entry) != 1) {
    exit(0);
}

In fact, this still allows the user to enter a negative number. Have you ever seen an array of a negative number of items? Seems strange to me, too... I think size_t would be a more appropriate type than int (and as a result, you'll need to use the %zu format specifier)...

Last but not least, gets is deprecated because it makes it impossible to prevent the user from overflowing buffers, which could cause segfaults.


#include <stdio.h>
#include <string.h>
int main(void)
{
    size_t entry;
    printf("\nPlease indicate the number of records you want to enter :\n");
    if (scanf("%zu",&entry) != 1)
    {
        exit(0);
    }

    char ent[entry][100000];
    printf("\nPlease input records of students (enter a new line after each record), with following format first name last name score \n");
    for(size_t i=0; i<entry; i++)
    {
        fgets(ent[i], sizeof ent[i], stdin);
        printf("%s",ent[i]);
    }
}

Upvotes: 2

kiviak
kiviak

Reputation: 1103

scanf("%d",entry);     //scanf("%d",&entry)
char ent[entry][100000]; //error

you should use malloc to get an array when you can not know the length of an array in compiling time

Upvotes: 1

icecity96
icecity96

Reputation: 1227

  1. you should use int main()instead of void main
  2. when you use you should scanf("%d",&entry) instead of scanf("%d",entry),what scanf need is an address.
  3. you shouldn't use gets(),it's dangerous,try fgets()

Upvotes: 1

Dilip Kumar
Dilip Kumar

Reputation: 1746

The error is in scanf use scanf("%d",&entry) instead of scanf("%d",entry);

Suggestion: use int as return type for main

Upvotes: 0

Related Questions