الشبكة العربية لمطوري الألعاب

مبتدئ  أحمد عبد العظيم مشاركة 1

Al Salamu Alaykum


I 'm implementing a function that returns a pointer to a struct, as follows

...

somestruct * funcname(int xx=0,int yy=0) {
           somestruct * mystruct = new somestruct;
           cout << "\n(a new struct object created on the heap)\n"; // or is it on the stack??
           mystruct->x=xx;
           mystruct->y=yy;
           return mystruct;
           }

...

int main(int argc, char *argv[])
{
    somestruct * mymainstruct = funcname(1,2);
    cout << "\n(my main struct created)\n";
    cout << mymainstruct->x;
    cout << "\n";
    cout << mymainstruct->y;
    cout << "\n";
    delete mymainstruct;
    cout << "\n(my main struct destroyed)\n";
    cout << "\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}

output is

(a new struct object created on the heap)
(my main struct created)
1
2
(my main struct destroyed)

my understanding is that I should 'delete' everything that was created with 'new'. I tried using 'delete mystruct' inside main (after 'delete mymainstruct'), but it gave an error (undeclared identifier).

so I have some questions here
first, using 'new' keyword inside the function as I did, am I creating the new struct object on the heap, or on the stack ? second, do I need to 'delete' this newly created object, or is it automatically deleted? am I causing memory leaks? and if I should use 'delete', where should it be?



thanks,

خبير  سلوان الهلالي مشاركة 2

وعليكم السلام،
مكان delete لا يسبب مشكلة هنا، ما هي رسالة الخطأ التي تحصل عليها بالضبط؟


إجابة على اسئلتك:
1. عندما تستخدم new فإنك تحجز ذاكرة ديناميكية من الـ heap
2. نعم يجب ان تستخدم delete لتحرير الذاكرة لأن سي++ لا تحرر ذاكرة الـ heap بشكل تلقائي، لا يهم مكان استخدام delete كل ما تحتاجه هو المؤشر للذاكرة المحجوزة، لكن تأكد من التخلص من المؤشر وعدم محاولة التعامل معه بعد delete لأن ذلك سيتسبب بدخول غير مصرح به للذاكرة

محترف مشرف عبد اللطيف حاجي علي مشاركة 3

The code you wrote is correct. funcname() creates a copy of "somestruct" and returns a pointer to it
The code in main() then takes this pointer, does something with it, then frees the allocated memory which this pointer points to

So all the memory you created is freed.

في 08 تشرين الثاني 2011 11:27 ص، غمغم أحمد عبد العظيم باستغراب قائلاً:

, am I creating the new struct object on the heap, or on the stack ?
Heap

بتاريخ 08 تشرين الثاني 2011 11:27 ص، قطب أحمد عبد العظيم حاجبيه بشدة وهو يقول:

do I need to 'delete' this newly created object, or is it automatically deleted?
You need to delete it. Otherwise you'll have a memory leak.

I think that you're confusing pointers with objects. Both mystruct inside funcname() and mymainstruct inside main() point to the same block in memory. So calling delete with any of them frees the allocated memory
And of course, you can't access the variable (or pointer) mystruct inside main(), since it has local scope.

Try to understand this, then ask yourself these questions:
1. Where am I creating the structure? heap or stack?
2. Where am I creating the pointer? heap or stack?
3. What is the relation between mystruct, mymainstruct and the structure object that I created using new in funcname?
4. What is the lifetime and the scope of these three variables/objects?

عبد اللطيف حاجي علي
مبرمج
In|Framez

مبتدئ  أحمد عبد العظيم مشاركة 4

thanks for  replying.

بتاريخ 12/ذو الحجة/1432 09:44 ص، قطب سلوان الهلالي حاجبيه بشدة وهو يقول:

مكان delete لا يسبب مشكلة هنا، ما هي رسالة الخطأ التي تحصل عليها بالضبط؟
`mystruct' undeclared (first use this function)

note that I'm using 'delete mystruct;' at the main scope

I think, like Abdul-Latif said, this error because I'm trying to access a pointer that no longer exists, if I got it right

وفي 12/ذو الحجة/1432 09:44 ص، أعرب عبد اللطيف حاجي علي عن رأيه بالموقف كالآتي:

I think that you're confusing pointers with objects. Both mystruct inside funcname() and mymainstruct inside main() point to the same block in memory. So calling delete with any of them frees the allocated memoryAnd of course, you can't access the variable (or pointer) mystruct inside main(), since it has local scope.
I see, so if I delete mynmainstruct i'm freeing the block of memory shared by both pointers , did I get that right?

I'm a beginner and new to pointers so yes, I'm still confused by them like you said
.

في 12/ذو الحجة/1432 09:44 ص، قال عبد اللطيف حاجي علي بهدوء وتؤدة:

Try to understand this, then ask yourself these questions:1. Where am I creating the structure? heap or stack?2. Where am I creating the pointer? heap or stack?
this is exactly what confuses me, could you please explain shortly these two cases: object on heap/stack, and pointer on heap/stack.

thanks

محترف مشرف عبد اللطيف حاجي علي مشاركة 5

وفي 08 تشرين الثاني 2011 12:01 م، أعرب أحمد عبد العظيم عن رأيه بالموقف كالآتي:

I see, so if I delete mynmainstruct i'm freeing the block of memory shared by both pointers , did I get that right?
Yes
For your other question, look at this code
int a=5;          // 1
int *p;           // 2
new int;          // 3
p = new int;      // 4
int *q = new int; // 5
q = &a;           // 6
The first line allocates an integer on the stack
The second line allocates a pointer to an integer. The pointer is allocated on the stack, but it might point to something allocated on the stack or heap.
The third line allocates an integer on the heap. Of course, since we're not saving it's address in another variable, it's pretty useless and will result in a leak.
The fourth line allocates an integer on the heap and assigns its address to the variable p. So the pointer p is on the stack, but it's pointing to something created by 'new' so it's pointing to an address on the heap.
I leave the fifth and sixth line for you.

عبد اللطيف حاجي علي
مبرمج
In|Framez

خبير  سلوان الهلالي مشاركة 6

mystruct معرف داخل إجراء funcname فقط وغير موجود في main
لكن delete mymainstruct معرف داخل main ولا مشكلة فيه


من الابسط ان تعتبر المؤشرات كارقام فقط، عندما تعرّف struct mystruct فسيحتوي mystruct على هيكل بيانات (object)، لكن عندما تعرف struct * mystruct فإن mystruct هنا هو رقم يمثل مكان حفظ هيكل البيانات في الذاكرة (عنوان) وليس هيكل بيانات فعلي، لذلك يمكنك نقله والتعامل معه وكأنه بالضبط قيمة int.


وبنفس الطريقة:
new لا تعيد object ولكنها تعيد رقم يمثل بداية الذاكرة التي تم حجزها. 
delete تأخذ ذلك الرقم/العنوان وتحذف الذاكرة المحجوزة له.


وسأترك الشرح المفصل لعبد اللطيف، اعتقد انه يقوم بكتابته الآن 😄

مبتدئ  أحمد عبد العظيم مشاركة 7

في 12/ذو الحجة/1432 10:16 ص، عقد سلوان الهلالي حاجبيه بتفكير وقال:

من الابسط ان تعتبر المؤشرات كارقام فقط، عندما تعرّف struct mystruct فسيحتوي mystruct على هيكل بيانات (object)، لكن عندما تعرف struct * mystruct فإن mystruct هنا هو رقم يمثل مكان حفظ هيكل البيانات في الذاكرة (عنوان) وليس هيكل بيانات فعلي، لذلك يمكنك نقله والتعامل معه وكأنه بالضبط قيمة int.
and this is what I'm trying to slowly grasp in order to clear up my confusion.

Thanks Sulwan.

وفي 12/ذو الحجة/1432 10:15 ص، قال عبد اللطيف حاجي علي متحمساً:

I leave the fifth and sixth line for you.
allocates a pointer 'q' on the stack which points to an integer on the heap

makes the pointer points to the address of variable 'a' which is allocated on the stack

what happens to the memory allocated to the integer on the heap in the previous step

is this a memory leak?

محترف مشرف عبد اللطيف حاجي علي مشاركة 8

وفي 08 تشرين الثاني 2011 12:49 م، قال أحمد عبد العظيم متحمساً:

allocates a pointer 'q' on the stack which points to an integer on the heapmakes the pointer points to the address of variable 'a' which is allocated on the stack
Exactly.

وفي 08 تشرين الثاني 2011 12:49 م، ظهر شبح ابتسامة على وجه أحمد عبد العظيم وهو يقول:

what happens to the memory allocated to the integer on the heap in the previous stepis this a memory leak?
 
That's a good question. Note that there are no calls to delete at all, so all the memory is going to leak.

Now, try to insert the correct delete statements to prevent memory leaks in the following code
{
  int a = 10;
  int *p = new int;
  {
     int *o = new int;
     int *q = new int;
     *o = 8;
     *q = 4;  
     *p = 5;
     p = q;
  }

  {
     *p = 1;
     p = &a;
  }
  *p = 2;
}
*p = 6; //@
What do you think about that last line?

عبد اللطيف حاجي علي
مبرمج
In|Framez

مبتدئ  أحمد عبد العظيم مشاركة 9

following the code, I understand that the last line assigns the value 6 to the memory location pointed to by pointer p
and pointer 'p' points at the memory location of variable 'a',
what happens to the 'new int' originally assigned to 'p' pointer?
and what happens to 'a' if I delete pointer 'p' now?
this is confusing

محترف مشرف عبد اللطيف حاجي علي مشاركة 10

Yes, you're following the code correctly. I intentionally left out the delete statements. So try to insert correct delete statement to free the allocated memory.

عبد اللطيف حاجي علي
مبرمج
In|Framez