C 指针重新分配导致分段错误
我在理解为什么不能为lastPrefix重新赋值时遇到了一个问题,在指定的行上,它给了我一个段错误。我似乎遗漏了一些基本的东西C 指针重新分配导致分段错误,c,pointers,double-pointer,C,Pointers,Double Pointer,我在理解为什么不能为lastPrefix重新赋值时遇到了一个问题,在指定的行上,它给了我一个段错误。我似乎遗漏了一些基本的东西 char * somefunc(char ** strs, int numStrings) { char * lastPrefix; printf("%d\n", *(strs[0]+0)); printf("%d\n", *(strs[1]+0)); printf("%d\n"
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));
}
我还可以为C指针提供一个好的参考吗?当您创建任何变量时,无论是指针还是数据,变量的初始值都将是一些垃圾或0。就你而言
char*lastprofix;
是这样一个变量,它包含一些垃圾值。您必须使用malloc()
或类似的方法为它指定一个有效值。或者,当您取消引用它时(*
),它可能指向一些不可访问的甚至不存在的内存位置。也许它指向了代码的中间部分。也许它指向NULL。这样的记忆在用户空间中是无法访问的。因此,windows(或linux)会杀死你的程序
你想做什么:
char*lastprofix;
lastPrefix=malloc(101)//最多可容纳100个字符的字符串
malloc()
将把值从堆中分配到变量中,程序应该可以正常工作。
只需记住在末尾释放内存:free(lastPrefix)代码>
类似地,在您的代码中,lastPrefix
指向一个未知地址,访问它会给您带来分段错误。*lastPrefix=*(strs[1]+0)
您正在取消引用的lastprifix
,该前缀未指向有效内存。
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 */