C/C++ Char Pointer Crash(C/C++ 字符指针崩溃)
问题描述
假设一个返回固定随机文本"字符串的函数写成这样
Let's say that a function which returns a fixed ‘random text’ string is written like
char *Function1()
{
return "Some text";
}
如果程序不小心试图改变doing的值,那么程序可能会崩溃
then the program could crash if it accidentally tried to alter the value doing
Function1()[1]=’a’;
函数调用之后的方括号是什么,试图这样做会导致程序崩溃?如果您熟悉这一点,任何解释将不胜感激!
What are the square brackets after the function call attempting to do that would make the program crash? If you're familiar with this, any explanation would be greatly appreciated!
推荐答案
您在函数中返回的字符串通常存储在进程的只读部分中.尝试修改它会导致访问冲突.(严格来说,这是未定义的行为,在某些系统中它会导致访问冲突.谢谢,约翰).
The string you're returning in the function is usually stored in a read-only part of your process. Attempting to modify it will cause an access violation. ( Strictly speaking, it is undefined behavior, and in some systems it will cause an access violation. Thanks, John).
这种情况通常是因为字符串本身与您的应用程序代码一起被硬编码.加载时,指针会指向您的进程中保存文字字符串的那些只读部分.事实上,每当您在 C 中编写一些字符串时,它都会被视为 const char*
(指向 const 内存的指针).
This is the case usually because the string itself is hardcoded along with the code of your application. When loading, pointers are stablished to point to those read-only sections of your process that hold literal strings. In fact, whenever you write some string in C, it is treated as a const char*
(a pointer to const memory).
这篇关于C/C++ 字符指针崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C/C++ 字符指针崩溃


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01