简体   繁体   中英

pointer reassignment gives segmentation fault

I'm having an issue understanding why I can't make the re-assignment for lastPrefix, on the line specified it gives me a segment fault. I appear to be missing something fundamental.

char * somefunc(char ** strs, int numStrings)
{
    char * lastPrefix;
    printf("%d\n", *(strs[0]+0));
    printf("%d\n", *(strs[1]+0));
    printf("%d\n", *(strs[2]+0));
    printf("%d\n", *(strs[0]+1));
    printf("%d\n", *(strs[1]+1));
    printf("%d\n", *(strs[2]+1));
    printf("%d\n", *(strs[0]+2));
    printf("%d\n", *(strs[1]+2));
    printf("%d\n", *(strs[2]+2));
    printf("%d\n", *(strs[0]+0));
    printf("%d\n", *(strs[1]+0));
    printf("%d\n", *(strs[2]+0)); // ALL IS WELL
    *lastPrefix  = *(strs[1]+0);
    *lastPrefix  = *(strs[2]+0);
    *lastPrefix  = *(strs[0]+1);  // WILL SEGMENT FAULT HERE
    *lastPrefix  = *(strs[1]+1);
    *lastPrefix  = *(strs[2]+1);


}


int main()
{

    char * strs[] = {
        "flower", "flow", "flight"
    };
    
    char * res = somefunc(strs, SIZEOF(strs));
}

Could I also ask for a good reference for C pointers?

When you create any variable, whether it's pointer or data, the initial value of the variable will be some garbage or 0. In your case,

char *lastPrefix;

Is such a variable, which contains some garbage value. You have to give it a valid value using malloc() or something like that. Or else, when you de reference it( * ), it might points to some inaccessible or even nonexistent memory location. Maybe it points to the middle of your code. Maybe it points to NULL. Memories like that is inaccessible in userspace. So, windows(or linux) kills your program.

What you want to do:

char *lastPrefix;
lastPrefix=malloc(101);   //holds strings upto 100 characters

The malloc() will allocate value into your variable from heap and the program should work okay. Just remember to free the memory at the end: free(lastPrefix);

int *ptr; // pointer variable declaration */

int kk; // actual variable declaration */

*a = 11; //  `a` pointing to unknown memory address and accessing this will give segmentation fault/

a = &kk; *a = 11 // This is valid. store address of `kk` in pointer variable  */

Similarily, in your code lastPrefix points to an unknown address, accessing it will give you segmentation fault.

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