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

查看:182
本文介绍了C / C ++字符指针崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,它返回一个固定的随机文本一个函数的字符串是这样写

Let's say that a function which returns a fixed ‘random text’ string is written like

char *Function1()
{ 
return "Some text";
}

然后程序会崩溃,如果不慎试图改变这样的价值

then the program could crash if it accidentally tried to alter the value doing

Function1()[1]=’a’;

什么是方括号中的函数调用试图这样做会使程序崩溃后?如果你熟悉这一点,任何的解释是大大AP preciated!

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).

这通常是因为字符串本身就是与应用程序的code沿着硬codeD的情况。装载时,指针配合建立指向您的过程中持有文字字符串的只读段。事实上,每当你写一些C字符串,它被视为一个为const char * (指针常量内存)。

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天全站免登陆