简体   繁体   English

指针重新分配导致分段错误

[英]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.我在理解为什么我不能对 lastPrefix 进行重新分配时遇到问题,在指定的行上它给了我一个段错误。 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?我还可以要求一个很好的 C 指针参考吗?

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,当您创建任何变量时,无论是指针还是数据,变量的初始值都会是一些垃圾或 0。在您的情况下,

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.你必须使用malloc()或类似的东西给它一个有效的值。 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.也许它指向NULL。 Memories like that is inaccessible in userspace.这样的记忆在用户空间中是无法访问的。 So, windows(or linux) kills your program.所以,windows(或linux)会杀死你的程序。

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. malloc()将从堆中分配值到您的变量中,程序应该可以正常工作。 Just remember to free the memory at the end: free(lastPrefix);只记得最后释放内存: 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.同样,在您的代码中lastPrefix指向一个未知地址,访问它会给您带来分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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