简体   繁体   中英

recieving signal SIGSEGV segmentation fault

#include<stdio.h>
#include<conio.h>

int main()
{

    int i, j, array[10] = { 1,2,3,4,5,6,7,8,9,10 };
    modify();

    for (i = 0; i<10; i++)
    {
        printf("Origional Array is:");
        printf(" %d\n", array[i]);

    }

    modify(array);

    for (i = 0; i<10; i++)
    {
        printf("New Array:");
        printf("%d\n", array[i]);
    }

    system("pause");
}

modify(int array[10])
{
    int j;
    for (j = 0; j<10; j++)
    {
        array[j] = array[j] * 3;
    }
    return array[j];
}

there is no compile time error... but at run time this show signal sigsegv segmentation fault. please help me...!

[Note that this answer assumes that the code is actually C and not C++]

There are a few problems with your code.

The fist is this:

modify();

Here you call the function, before you have told the compiler that it exists. Apparently your compiler says it's okay, which it really isn't. What probably is happening is that the compiler deduces (fancy word for "guessing") that the function takes no arguments and returns nothing. Ie that the declaration look like

void modify(void);

This "guessing" was allowed in older standards of C, but since the C99 standard this implicit declaration was removed and would give you an error in a compliant compiler.

A little later you do

modify(array);

which once again calls the function, but since the compiler thinks that the function doesn't take any arguments, none will actually be passed. Which leads to the worst problem of all: In the actual modify function you use an argument, but since none is actually passed the variable will not be initialized and you will have undefined behavior trying to dereference that pointer (arrays decays to pointers when passed as arguments to functions) and you will most likely have your crash there.

There also the returning from the function:

return array[j];

Here the value of j will be 10 which is out of bounds for the array you pass (well, try to pass) to the function.

To solve the problem, add the function prototype declaration somewhere before calling the function, a usual place would be in the global scope just before the main function. Something like

...
int modify(int *array);

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

And fix the return statement in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM