在C中初始化一个char指针.为什么认为这很危险? [英] Initializing a char pointer in C. Why considered dangerous?

查看:116
本文介绍了在C中初始化一个char指针.为什么认为这很危险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
char s和有什么区别[ ]和char * s在C中?

Possible Duplicate:
What is the difference between char s[] and char *s in C?

我初始化一个char指针:

char *a="test";

我在某些地方读过,这被认为是 只读 ,并且很危险.

I have read at some places that this is considered read-only and that it's dangerous.

这是否意味着"test"没有在堆中分配空间?这是否意味着字符串"test"可以稍后在程序中覆盖?

Does that imply that the "test" is not allocated space in the heap? Does that mean that the string "test" can be written over later in the program?

---扩展我的问题---

如果我如上所述对a进行了初始化,那么我会进行其他一系列初始化,例如:

If I have initiliazed a as above and then I do a bunch of other initializations like:

int b=20;
char c[]="blahblahblah";

内存中的测试"会被"20"或"blah"覆盖吗?还是这种情况没有根据?

Can "test" in memory get overwritten with "20" or "blah"? Or does that scenario have no ground?

推荐答案

这很危险,因为字符串不可修改.尝试这样做会导致 未定义的行为 .

This is dangerous because the string is not-modifiable. Attempting to do so results in undefined behavior.

因此最好这样做:

const char *a = "test";

您是正确的,在这种情况下,"test"没有分配在堆或堆栈*上,而是位于不可修改的静态内存中.

You are correct that "test" in this case is not allocated on the heap or the stack* and instead lies in static memory that is not-modifiable.

*该标准对堆栈或堆一无所获,尽管通常是这样实现的.

*The standard says nothing about the stack or heap, though that's how it's usually implemented.

另一方面:

char a[] = "test";

可以安全修改,因为它只是以下形式的缩写:

Is safe to modify since it's just short-form for:

char a[] = {'t','e','s','t','\0'};

这是一个普通的可修改数组.

which is an ordinary modifiable array.

这篇关于在C中初始化一个char指针.为什么认为这很危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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