Home > Enterprise >  Segmentation fault (core dumped) Error on pointers in C
Segmentation fault (core dumped) Error on pointers in C

Time:02-25

I met a problem in c like blow, for instance if i wish to find a item in an array with index equals 3 then return the address of the item found. edit index in another place while affact original item in the array. But how does this gonna work in code, any suggestion or help?

I wrote code in below but got Segmentation fault (core dumped) Error;

#include <stdio.h>
#include <unistd.h>


typedef struct toT
{
    int index;
}toTs;


toTs lst[3];

toTs *try()
{   
    int i;
    for(i = 0; i < 3; i  )
    {
        toTs *current = &lst[i];
        printf("%d\n", current->index);
        if(current->index == 3)
        {
            printf("test work");
            return *current;
        }
        
    }
}

int main()
{

    int i;

    for(i = 0; i < 3; i  )
    {
        lst[i].index = i;
    }

    for(i = 0; i < 3; i  )
    {
        printf("test %d\n", lst[i].index);
    }

    toTs *now;
    now = try();
    
    now->index = 30;

    printf("current %d\n", now->index);
    printf("current %d\n", lst[2].index);
}

thanks so much for helping me on this issue!!!!!

CodePudding user response:

Most errors are here

toTs* try()
{
    int i;
    for (i = 0; i < 3; i  )
    {
        toTs* current = &lst[i];
        printf("%d\n", current->index);
        if (current->index == 3)
        {
            printf("test work");
            return *current;
        }

    }
}

First you must return a value all the time even if you dont find anything in the loop. You should probably return NULL if you dont find it. My compiler issued a warning about it.

1> warning C4715: 'try': not all control paths return a value

Always pay attention to warnings, the compiler is trying to help.

Second the return type is toTs * but you do

 return *current;

that is a toTs, not a toTs *. ON my machine this is a fatal compile error, its hard to beleive that you dont have the same thing. My guess is that you tried that change, it didnt work and so you left it in when cutting and pasting.

Finally you load 3 elemts into lst, with index values 0,1,and 2. So you never find 3.

So fixing this gives

toTs* try()
{
    int i;
    toTs *current = NULL;
    for (i = 0; i < 3; i  )
    {
        current = &lst[i];
        printf("%d\n", current->index);
        if (current->index == 2)
        {
            printf("test work");
            break;
        }

    }
    return current;
}

finally you need to see if NULL is returned

toTs* now;
now = try();
if (now == NULL)
{
    printf("not found");
}
else
{

    now->index = 30;
    printf("current %d\n", now->index);
    printf("current %d\n", lst[2].index);
 }
  •  Tags:  
  • c
  • Related