C/C++ 字符指针崩溃 [英] C/C++ Char Pointer Crash

查看:35
本文介绍了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++ 字符指针崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆