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++ 字符指针崩溃
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01