We can compile the following program using the gcc compiler.
But when running it, we get a segmentation fault.
Why ?
#include <stdio.h>
int main()
{
// The following statement is equal to " constant char* filename = "file1.txt"; "in c++
char* filename = "file1.txt"; // Initialization and after that filename points to a constant string.
printf("\nPlease input for the filename ==> ");
scanf("%s", filename); // Try to modify a constant string. It will cause a segmentation fault !
printf("\nThe file name you have input is %s", filename);
return 0;
}
本文通过一个简单的C语言程序示例介绍了尝试修改常量字符串时导致的段错误。该程序尝试通过scanf函数修改一个初始化为常量字符串的指针变量,这违反了常量内存区域的保护机制。
2636

被折叠的 条评论
为什么被折叠?



