gpt4 book ai didi

c++ - new(堆或堆栈)创建的结构字段在哪里?

转载 作者:太空狗 更新时间:2023-10-29 21:06:04 26 4
gpt4 key购买 nike

我读过栈和堆但我不知道这个

x 在哪里(在堆中还是在栈中)?我的代码是否存在内存泄漏?

struct st
{
int x;
int* y;
};

st* stp;

void func()
{
st* s=new st();

s->x=2;
s->y=new int(5);

stp=s;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{

func();

cout << stp->x << " " << *stp->y <<endl;

delete stp->y;
delete stp;
}

输出2 5

最佳答案

stp 是动态分配的,因此在堆上。* 因此,它的所有成员(包括 x)都在堆。

据我所知,您没有内存泄漏。


* 从技术上讲,C++ 标准不讨论堆栈与堆,因此由编译器决定分配内容。但实际上,它会存储在类似堆的结构中。

关于c++ - new(堆或堆栈)创建的结构字段在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com