分割故障 - 字符指针 [英] Segmentation fault - char pointer
问题描述
在下面的code,该行:
*年底= *前;
给出了一个分段错误。我在这里问类似的问题 ,但我不知道这是因为我有NUM的两个副本。请解释为什么它的SEG-断层。谢谢你。
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;字符* getPalin(字符* NUM);诠释的main()
{
字符* NUM =(字符*)malloc的(100); NUM =123456; 的printf(%S \\ n,getPalin(NUM)); 返回0;
}字符* getPalin(字符* NUM)
{
INT长度= strlen的(NUM); 如果(长度%2 == 0)
{
字符*前NUM =;
字符*结束= NUM +的strlen(NUM) - 1; //指针结束 而(前面!= NUM +(长/ 2))//指针没有中间还
{
*结束= *前; 的printf(%C,*结束); 前++;
\t\t结束 - ;
}
} 返回NUM;
}
这两条线:
的char * NUM =(字符*)malloc的(100);
NUM =123456;
具有以下的效果。
第100分配字节数和集 NUM
指向这些字节。
第二个变化NUM指向字符串123456,这是几乎可以肯定在只读存储器中。
任何试图更改只读存储器中的内容,将导致一个分段违例。您需要将字符串复制到的malloc
'D NUM
试图改变它,与之前:
的strcpy(NUM,123456);
这是你应该有,你目前拥有的行:
NUM =123456;
In the code below, the line:
*end = *front;
gives a segmentation fault. I asked a similar question here but I'm not sure if this is because I have two copies of num. Please explain why it's seg-faulting. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getPalin(char* num);
int main()
{
char* num = (char*)malloc(100);
num = "123456";
printf("%s\n", getPalin(num) );
return 0;
}
char* getPalin(char* num)
{
int length = strlen(num);
if ( length % 2 == 0 )
{
char* front = num;
char* end = num + strlen(num) - 1; //pointer to end
while( front != num + (length/2) ) //pointers not middle yet
{
*end = *front;
printf("%c", *end);
front++;
end--;
}
}
return num;
}
These two lines:
char* num = (char*)malloc(100);
num = "123456";
have the following effect.
The first allocates 100 bytes and sets num
to point to those bytes.
The second changes num to point to the string "123456" which is almost certainly in read-only memory.
Any attempt to change the contents of read-only memory will result in a segmentation violation. You need to copy the string into the malloc
'd num
before attempting to change it, with:
strcpy (num, "123456");
That's the line you should have where you currently have:
num = "123456";
这篇关于分割故障 - 字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!