Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
929 views
in Technique[技术] by (71.8m points)

c - Segmentation fault - char pointer

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
", 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...