2011-03-01 24 views
3

鉴于以下程序。谁引发了分段错误?

int main() { 
char *str = "hello word"; 
str[0] = 'a'; 
return 0; 
} 

上面的程序抛出了段错误。我知道它会抛出,因为只读段包含hello世界,并且它不能被修改。如果在L1缓存(处理器内)中完成从“h”变为“a”的存储指令,并且只有当页面从L3刷新到主存时,MMU才会进入画面,谁会立即抛出分段错误。

下面的代码是有效地做同样的事情,不会导致任何分段错误。为什么?

int main() { 
char str[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'}; 
str[0] = 'a'; 
return 0; 
} 

回答

3

处理器高速缓存具有与每个高速缓存行关联的标签,告诉它应用于当前在该高速缓存行中保存的内存的权限。因此,尝试写入缓存时,尝试写入只读内存将(通常)立即被捕获;它不会等到该缓存行被刷新到主内存。

只要两个示例之间的区别变得非常简单:第一个定义了一个静态分配的字符串文字。试图修改该字符串会导致未定义的行为。第二个定义了一个被初始化为一个特定值的char数组 - 但是在初始化之后,它就像其他数组一样。特别是,修改数组内容的结果已被很好地定义。

+0

那么,你的意思是缓存控制器正在抛出异常? – Boolean 2011-03-01 05:10:01

+1

@Bala:无论如何,部分CPU无论如何 - 我不相信AMD或Intel会指定特定的异常来自缓存控制器还是“内存写入”功能单元。这种情况甚至可能因CPU而异。 – 2011-03-01 05:14:09

+0

-1,第一个字符串分配在只读段中,第二个字符串分配在堆栈上。在这两种情况下,它都是字符数组。 – 2011-03-01 15:32:17

2

在第二个,你正在复制。而在第一次你不是。

char str[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'}; 

这里str是在堆栈上创建的数组。至str,正在复制内容。如何永远在 -

char *str = "hello word"; 

str指向数据驻留在不可修改的部分。所以,你不能和什么时候尝试结果分段错误。


说明征求意见

我不认为,对于原始数据类型C和C++变化它的规则。从ISO/IEC 14882:2003(E),8.5.2节

1. A char array (whether plain char, signed char, or unsigned char) can be 
    initialized by a string- literal (optionally enclosed in braces); a wchar_t 
    array can be initialized by a wide string-literal (option- ally enclosed in 
    braces); successive characters of the string-literal initialize the members of 
    the array. 

    [Example: 
      char msg[] = "Syntax error on line %s\n"; shows a character array 
      whose members are initialized with a string-literal. Note that because 
      ’\n’ is a single character and because a trailing ’\0’ is appended, 
      sizeof(msg) is 25. 
    ] 

2. There shall not be more initializers than there are array elements. 

    [Example: 
      char cv[4] = "asdf" ;// error is ill-formed since there is no space for the implied trailing ’\0’. 
    ] 

所以,例如2清除怀疑。

+0

你能详细解释一下吗? – Boolean 2011-03-01 05:09:27

+0

另外,不需要NULL终止字符。它在第二种情况下默认添加。 – Mahesh 2011-03-01 05:14:08

+0

这实际上是在C标准中规定的吗? – 2011-03-01 05:17:51