内存错误:Address .... is on thread 1's stack 与创建变量时出现段错误

内存错误:Address …. is on thread 1’s stack 与创建变量时出现段错误

标签: 内存错误 段错误

by 小威威

今天对代码进行内存检测的时候,发现出现了以下问题:

Invalid write of size 8
       at 0x400AB9: test_1() (main.cpp:6)
       by 0x401521: main (main.cpp:106)
     Address 0x7fed236d8 is on thread 1's stack

    Invalid read of size 8
       at 0x4015D4: person::person() (world.h:9)
       by 0x401521: main (main.cpp:106)
     Address 0x7fed236d8 is on thread 1's stack

    Invalid write of size 1
       at 0x401622: group::group(bool) (world.h:15)
       by 0x400B01: test_1() (main.cpp:7)
       by 0x401521: main (main.cpp:106)
     Address 0x7fef0bba0 is on thread 1's stack

    Invalid write of size 1
       at 0x4016D6: group::group(bool) (world.h:18)
       by 0x400B01: test_1() (main.cpp:7)
       by 0x401521: main (main.cpp:106)
     Address 0x7fef0bba1 is on thread 1's stack

    Invalid write of size 1
       at 0x401622: group::group(bool) (world.h:15)
       by 0x400B15: test_1() (main.cpp:7)
       by 0x401521: main (main.cpp:106)
     Address 0x7fee17940 is on thread 1's stack

    Invalid write of size 4
       at 0x401628: group::group(bool) (world.h:15)
       by 0x400B15: test_1() (main.cpp:7)
       by 0x401521: main (main.cpp:106)
     Address 0x7fef0bb84 is on thread 1's stack

    Invalid write of size 4
       at 0x401636: group::group(bool) (world.h:15)
       by 0x400B15: test_1() (main.cpp:7)
       by 0x401521: main (main.cpp:106)
     Address 0x7fef0bb88 is on thread 1's stack
     ...

然后我跟着错误信息去看源代码发现,有些内存错误竟然出现在实例化对象上(也就是创建变量上)。这令我感到非常奇怪,创建一个变量怎么会有内存错误

最终我认为只有一种情况,那就是爆栈。根据我所查的资料,一个程序所能申请的栈空间大小为1M,如果超过了1M的限制,就会导致爆栈。

例如我的代码中出现下面一段:

struct Node {
    bool a[1000][1000];
};

Node node[10];

我们来计算一下,一个bool类型的变量为1字节,那么1000*1000就相当于2^20字节,即a数组的大小是2^20字节。暂且认为结构体大小就等于数组大小,然后开一个长度为100的数组,那么这个结构体数组的大小就是2^20*10即2^23字节。然后我们将其转换成兆,那么字节就要两次除以2^10,得2^3 = 8M > 1M, 显然爆栈了。

如果结构体数组长度定义得更大,或者a数组本身定义得更大,可能就会出现在创建变量时发生段错误,导致程序异常终止

因此,类的成员变量或者函数内不能将数组开的太大。尤其是二维数组。一般来说开100*100以下还属正常,但也不排除不会出错,这都是依据自己代码而定,主要是要学会自己去判断。当超过100*100时就要注意了,那就一定要去计算会不会有爆栈的可能。

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!

你可能感兴趣的:(内存,编译错误,段错误,爆栈)