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++ 字符指针崩溃
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
