Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Why does writing to a string literal in this C program segfault?

#include<stdio.h>

void main()
{
    char *p="nyks";

    p[2]='n';

    printf("%s",p);
}

This crashes with a SEGMENTATION FAULT. Can someone explain why?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

It is undefined behavior to try to overwrite a string literal. C99 §6.4.5/6:

If the program attempts to modify such an array, the behavior is unde?ned.

This is restated in Appendix J.2 (undefined behavior).

If you instead do:

char p[] = "nyks";

you can allocate and initialize an automatic (stack) character array. In that case, it is perfectly fine to modify elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...