qq_29879731 2017-06-30 03:22 采纳率: 0%
浏览 929

关于局部变量内存分配以及static关键字的问题

#include
#include
#include
using namespace std;
void test2(int count) {
printf("%d count:%d\n", this_thread::get_id(), count);
int ef[count];
int d[5];
printf("%d %d %p %d\n",this_thread::get_id(), count, d, sizeof(d));
static int a[5];
printf("%d %d %p %d\n", this_thread::get_id(), count, a, sizeof(a));
int b[5];
printf("%d %d %p %d\n", this_thread::get_id(), count, b, sizeof(b));
sleep(5);
}
void test() {
int count = 1;
while(count+=100){
test2(count);
}

}
int main() {
printf("Hello world!\n");
thread t1(test);
thread t2(test);
t1.join();
t2.join();
return 0;
}
我的编译器里这份代码中a,b,d的地址始终不变,理论上来说不应该不变呀,这应该是编译器的优化吧?
还有,我就是觉得static变量其实是在编译器就分配内存并不作改动,想验证这个,结果发现不止static变量地址不会变化普通定长数组地址也不改动,那岂不是很尴尬么。。。。我觉得我的想法是对的,因为static变量在不同线程中也不同,另一方面,百度发现确实这样。。。。
我的电脑上运行结果如下:
Hello world!
-990759168 count:101
-990759168 101 0x7f9fc4f22de0 20
-990759168 101 0x604180 20
-990759168 101 0x7f9fc4f22e00 20
-999151872 count:101
-999151872 101 0x7f9fc4721de0 20
-999151872 101 0x604180 20
-999151872 101 0x7f9fc4721e00 20
-990759168 count:201
-990759168 201 0x7f9fc4f22de0 20
-990759168 201 0x604180 20
-990759168 201 0x7f9fc4f22e00 20
-999151872 count:201
-999151872 201 0x7f9fc4721de0 20
-999151872 201 0x604180 20
-999151872 201 0x7f9fc4721e00 20
-990759168 count:301
-990759168 301 0x7f9fc4f22de0 20
-990759168 301 0x604180 20
-990759168 301 0x7f9fc4f22e00 20
-999151872 count:301
-999151872 301 0x7f9fc4721de0 20
-999151872 301 0x604180 20
-999151872 301 0x7f9fc4721e00 20

  • 写回答

3条回答 默认 最新

  • threenewbee 2017-07-01 16:24
    关注

    相同的代码,相同的编译选项,在相同的编译器上编译,静态变量地址不变很正常。

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料