分段错误 - 字符指针 [英] Segmentation fault - char pointer
问题描述
在下面的代码中,行:
*end = *front;
给出分段错误.我问了一个类似的问题 here 但我不确定这是否是因为我有num 的两个副本.请解释为什么它是段错误.谢谢.
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
", 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;
}
推荐答案
这两行:
char* num = (char*)malloc(100);
num = "123456";
有以下效果.
第一个分配 100 个字节并设置 num
指向这些字节.
The first allocates 100 bytes and sets num
to point to those bytes.
第二个更改 num 指向字符串123456",几乎可以肯定它在只读内存中.
The second changes num to point to the string "123456" which is almost certainly in read-only memory.
任何更改只读内存内容的尝试都将导致分段违规.在尝试更改它之前,您需要将字符串复制到 malloc
的 num
中,使用:
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屋!