1

I am new to C programming, I am trying to run a code snippet that create a dynamic array of struct object and then uses scanf to save values. When I run the code in code blocks it works just fine but throws memory access exceptions in Visual studio 2019

I am attaching code snippet and error trace.

    struct Student
{
    int rollNumber;
    char studentName[10];
    float percentage;
};

int main(void)
{
    int counter;
    struct Student studentRecord[5];

    printf("Enter Records of 5 students");

    for (counter = 0; counter < 5; counter++)
    {
        printf("\nEnter Roll Number:");
        scanf_s("%d", &studentRecord[counter].rollNumber);
        printf("\nEnter Name:");
        scanf_s("%s", &studentRecord[counter].studentName);
        printf("\nEnter percentage:");
        scanf_s("%f", &studentRecord[counter].percentage);

    }

    printf("\nStudent Information List:");

    for (counter = 0; counter < 5; counter++)
    {
        printf("\nRoll Number:%d\t Name:%s\t Percentage :%f\n",
            studentRecord[counter].rollNumber, studentRecord[counter].studentName, studentRecord[counter].percentage);
    }
    return 0;
}

Error:

Exception thrown at 0x7C9AEF8C (ucrtbased.dll) in linkedList.exe: 0xC0000005: Access violation writing location 0x00500000.

  • `scanf_s("%s", &studentRecord[counter].studentName);`: The `&` should not be there, but I'm not sure if that would cause your crash. – Nate Eldredge May 16 '21 at 23:45
  • `scanf_s` needs different arguments with `%s`. [Check out the documentation](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/scanf-s-scanf-s-l-wscanf-s-wscanf-s-l?view=msvc-160), or switch to plain `scanf` (with `"%9s"` to avoid buffer overflow) for now. – Nate Eldredge May 16 '21 at 23:46
  • Since I can't reproduce on mac with visual studio code, here is a reference https://stackoverflow.com/questions/18836661/header-for-scanf-s-function if it helps – thirdeye May 17 '21 at 00:22
  • also, http://www.cplusplus.com/forum/beginner/2300/ if this helps. – thirdeye May 17 '21 at 00:30

1 Answers1

0

You need to specify the size of the buffer (in characters) for the string format specifier, ie %s.

scanf_s( "%9s", studentRecord[ counter ].studentName, 10 );
WBuck
  • 5,162
  • 2
  • 25
  • 36