Access Violation Exception in Visual Studio

Asked 2 years ago, Updated 2 years ago, 45 views

#include <stdio.h>
#include <string.h>

int string_length(char* str) {
    char* ptr = str;

    int length = 0;
    while (*(ptr++) != '\0')
        length++;
    return length;
}


char comma(char* str) {
    static char result[100];
    int length;
    int index = 0;

    length = string_length(str);

    for (int i = 0; i < length; i++) {
        if ((length - i) % 3 == 0 && i != 0)
            result[index++] = ',';
        result[index++] = *(str + i); // = str[i]
    }
    result[index] = '\0';

    return result;


}




int main(void)
{
    char str[100];

    printf ("Enter an integer: ");
    scanf_s("%s", str, sizeof(str));

    printf("%s\n", comma(str));

    return 0;
}

I kept turning it into a visual studio Exception occurred (0x00007FFD2BA02487 (ucrtbased.dll), pointer.exe): 0xC0000005: 0x0000000070 Access violation occurred while reading location. There is an error like this, but I don't know even if I search for it. Google said scanf_s is the problem, but they also specified a buffer Is there any reason for this error to appear?

c visual-studio

2022-09-20 10:26

1 Answers

char comma(char* str) {

Change the line above as below.

char* comma(char* str) {


2022-09-20 10:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.