23、关于字符串常量存储的一个易犯错误的地方

简介: 1、如下示例程序中: 示例代码 // Win32_test.cpp : 定义控制台应用程序的入口点。 #include "stdafx.h" #include "iostream" using namespace std; int _tmain(int argc, _TCHA...

1、如下示例程序中:

示例代码

// Win32_test.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	char *a = "hello";
	char *b = "hello";
	char s[] = "hello";
	//*b = 'b'; error
	s[0] = 'b';
	//a,b指针指向的是常量区的数据"hello”,而s[]在栈中分配内存并复制了
	//常量数据"abcdef”的拷贝。所以,我们修改字符数组s,实际上只是修改的在
	//栈中的拷贝,而没有修改文本常量区的数据。
	if (a == b)
		cout << "a == b" << endl; //输出a == b
	if ("test" == "test")
		cout << "test == test" << endl; //输出test == test
	return 0;
}
示例 代码
#include <stdio.h> 
int main() 
{ 
	char *p="abcdef"; //should be : const char * p = "abcdef";
	//...
} 
/*
apparently, var p is allocated from current stack frame, 
the string constant literal: "abcdef" lies in the .rdata segment,
if u use the expresstion: p[2]='W', which will change the rdata's data,
os refuse this action, but the compiler and linker pass.
so a running-error will popup.
*/

//another ex;
#include <stdio.h> 
int main() 
{ 
	char s[]="abcdef";//s在栈,“abcdef”在数据区
	//...
} 
/*
this behavior is okay, 
this memory from s is alloated from the current stack frame,
r-vale "abcdef" will be copies to that place that is already allocated 
through above step. notice! u change only the copy NOT origin, so this program 
may support 'reload'.

    可能我们觉得他们不会相等,实际是相等的,为什么?因为他们是字符串常量,存储在内存中的文字常量区(文字常量区—常量字符串就是放在这里的,程序结束后由系统释放)[2]

2、在[1]中,作者作出了相反的答案。但至少在我的电脑上,VS2008中,执行的是如程序中的结果,与[1]中所述有区别。

3、在[3]CSDN论坛的帖子中,对这个问题进行了讨论。

示例代码

//main.cpp
 int a=0;  //全局初始化区
 char *p1;  //全局未初始化区
 main()
 {
  intb;栈
  char s[]="abc";  //栈
  char *p2;     //栈
  char *p3="123456";  //123456\0在常量区,p3在栈上。
  static int c=0;  //全局(静态)初始化区
  p1 = (char*)malloc(10);
  p2 = (char*)malloc(20);  //分配得来得10和20字节的区域就在堆区。
  strcpy(p1,"123456");  //123456\0放在常量区,编译器可能会将它与p3所向"123456"优化成一个地方。
}

参考

[1] http://www.soidc.net/articles/1215485053486/20061202/1215945550035_1.html

[2] http://blog.163.com/zhoumhan_0351/blog/static/39954227200910288840539/

[3]http://topic.csdn.net/u/20081106/23/02545709-f008-41c5-86d0-d2eb8aa1e162_2.html

目录
相关文章
|
Web App开发 安全 数据安全/隐私保护
|
8天前
|
人工智能 运维 安全
|
6天前
|
人工智能 异构计算
敬请锁定《C位面对面》,洞察通用计算如何在AI时代持续赋能企业创新,助力业务发展!
敬请锁定《C位面对面》,洞察通用计算如何在AI时代持续赋能企业创新,助力业务发展!
|
8天前
|
机器学习/深度学习 人工智能 自然语言处理
B站开源IndexTTS2,用极致表现力颠覆听觉体验
在语音合成技术不断演进的背景下,早期版本的IndexTTS虽然在多场景应用中展现出良好的表现,但在情感表达的细腻度与时长控制的精准性方面仍存在提升空间。为了解决这些问题,并进一步推动零样本语音合成在实际场景中的落地能力,B站语音团队对模型架构与训练策略进行了深度优化,推出了全新一代语音合成模型——IndexTTS2 。
663 23
|
7天前
|
人工智能 测试技术 API
智能体(AI Agent)搭建全攻略:从概念到实践的终极指南
在人工智能浪潮中,智能体(AI Agent)正成为变革性技术。它们具备自主决策、环境感知、任务执行等能力,广泛应用于日常任务与商业流程。本文详解智能体概念、架构及七步搭建指南,助你打造专属智能体,迎接智能自动化新时代。
|
14天前
|
人工智能 JavaScript 测试技术
Qwen3-Coder入门教程|10分钟搞定安装配置
Qwen3-Coder 挑战赛简介:无论你是编程小白还是办公达人,都能通过本教程快速上手 Qwen-Code CLI,利用 AI 轻松实现代码编写、文档处理等任务。内容涵盖 API 配置、CLI 安装及多种实用案例,助你提升效率,体验智能编码的乐趣。
1072 110
人工智能 数据可视化 数据挖掘
241 0