Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

c++ - Does a function returning the value of a pointer to a new[] array leaks memory after returning the result?

I've read that we need to delete pointers after pointing it to a value address created with the keyword "new". But I need to get the values inside of an array and return it to a variable, so I wrote this function:

GLfloat VertexArray(Vertex<GLfloat> v1, Vertex<GLfloat> v2, Vertex<GLfloat> v3) {
    GLfloat *ArrayPtr = new GLfloat[24]{ v1.x, v1.y, v1.z, v1.w, v1.r, v1.g, v1.b, v1.a,
                                         v2.x, v2.y, v2.z, v2.w, v2.r, v2.g, v2.b, v2.a,
                                         v3.x, v3.y, v3.z, v3.w, v3.r, v3.g, v3.b, v3.a };
    return *ArrayPtr;
};

Is this bad? If so, is there a better way to return the entire array?

question from:https://stackoverflow.com/questions/66049700/does-a-function-returning-the-value-of-a-pointer-to-a-new-array-leaks-memory-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes it's bad. It's a memory leak because the allocated array is never deleted (as you said).

Here's a version that doesn't leak

GLfloat VertexArray(Vertex<GLfloat> v1, Vertex<GLfloat> v2, Vertex<GLfloat> v3) {
    return v1.x;
};

No allocation is needed for the function you wrote, because the only value you are returning is the first in your array which is v1.x.

Now this is a rather pointless function, so maybe your real code is more complicated than the code you posted.

Maybe you meant to write a function that returns the whole array. In that case return the pointer that you allocated return ArrayPtr;. In that case you still need to delete the pointer, but you can do it somewhere in the code that called this function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...