Arrays and structs for memory usage and leaks

This is a logical question.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <cassert>     // What is this header used for ?


// Imagine building this struct of array for usage.
struct str_x {
    string* array; 
    int size; 
};

str_x initiate (int sizeArray = 3){
   str_x array;
   array. size = sizeArray;
   array. array = new string [25];
  
   return array;
}


Imagine you want to have a program that gets strings from the user input, and wants to arrange and replace these strings every often. Most of us know about the MEMORY LEAKS that can happen, so we have to deallocate our arrays using delete [] arr;

Questions:

1) Why is it useful to build a struct of arrays instead of creating an array in every function (imagine using functions of string and void later in the program)?

My guess: Struct can act as a temporary memory storage which can hold arrays and their size and it is easier to pass it as array pass by reference parameter.


2)

1
2
3
struct str_x {
    //...
};

Is str_x a name ? what does str stands for ?


3)
I know str_x is for the struct, but what does it do if we add array to it ?

1
2
3
4
   str_x array;
   array. size = sizeArray;
   array. array = new string [25];
  


4) new string allocates free_store (free memory location) to the array. But, does the 25 represent the size of it ?


5) Will a problem happen if the size of the array is 3 while we are allocating size of 25 ?



I have a hard time understanding the logic. I am a first year student learning c++, so please use simple language if you can. Thank you :)
Last edited on
Please answer my questions in order according to number because it is easier for me and others to follow your explanation.


So you can paste the answers directly into your homework assignment.
This is not my homework assignment my friend. I finished my assignment 3 days ago, but with the help of a friend, so I didn't get a chance to learn the material in depth. Now I am going through my program again and finding the areas that I lack in understanding, and that is why I generated my own questions one by one. I ask for help, but step by step, so I don't get lost in explanations and I can easily follow.

One's perception of a situation is not always right.
Last edited on
Guys, I really want to learn.

I appreciate any help.
closed account (48T7M4Gy)
Why not make an attempt at the answers, even though they are your own questions? FWIW the answer you have given for your first question is reasonable. I'd add the more technical term to what you are saying, 'encapsulation'. Feel free to google that term.

Now on to question 2. What do you think 'str' stands for? And does it really matter? ( Hint: str even though it probably doesn't stand for 'stands to reason', it probably stands for something closer to the pragram context and provides a bit of a memory jogger in a large program. ) Feel free to read http://www.cplusplus.com/doc/tutorial/structures/
Last edited on
@kemort, thank you for your response. Yes I wrote these questions myself because I am trying to focus on the understanding aspect of it.

1)
I see, hmmm, that is interesting, I wonder how is it possible to connect classes and objects to structs as part of encapsulation process ?

2) Yeah, I thought it might do something special, but I guess maybe just allocating memory to the necessary array inside our struct.


Then I give my own attempt for each question, you confirm the information.

4)
new string allocates memory to the array at free store or heap which is a free memory location in RAM, but I have hard time understanding if [25] means we are assigning 25 to location i = 0 of the array or we are creating 25 different location i = 0 ... i = 24 ?

 
array. array = new string [25];


5) I also think that a compiler error will occur due to the fact that the size of the array is 3, but we are giving it new string [25] ? Does this even make sense ?





Last edited on
closed account (48T7M4Gy)
Yes I wrote these questions myself because I am trying to focus on the understanding aspect of it.
Excellent, so moving on :)

1)
I see, hmmm, that is interesting, I wonder how is it possible to connect classes and objects to structs as part of encapsulation process ?
Well, classes and structs are similar in that they both primarily encapsulate disparate data types into user-defined 'types' just like int's, double's etc. Objects are instances of those types. Classes are 'sophisticated' structs which incorporate 'data-hiding' and several other differences. You should read up on in the tutorials here and elsewhere at your leisure.

2) Yeah, I thought it might do something special, but I guess maybe just allocating memory to the necessary array inside our struct.
Its just a name. Why don't you change the name in the program and try it yourself eg struct stands_to_reason { etc and create a stands_to_reason object.

Then I give my own attempt for each question, you confirm the information.
that's the way.

4)
new string allocates memory to the array at free store or heap which is a free memory location in RAM, but I have hard time understanding if [25] means we are assigning 25 to location i = 0 of the array or we are creating 25 different location i = 0 ... i = 24 ?


Maybe it would be clearer if you want an array of 25 strings to write

string *array = new string[25];

You will need to have a corresponding delete[]

http://stackoverflow.com/questions/14993791/in-c-how-to-write-a-destructor-for-freeing-memory-of-pointer-to-a-structure

http://stackoverflow.com/questions/15938108/destructor-of-arrays-of-pointers-in-structures

array. array = new string [25];

5) I also think that a compiler error will occur due to the fact that the size of the array is 3, but we are giving it new string [25] ? Does this even make sense ?
If the array has 25 elements and you only use 3 then there is no problem. However if the number varies from object to object why not make the size a (dynamic) parameter in creating the object and use that instead of the constant 25 value.
Last edited on
1 and 2) Ok, interesting, my prof is going to talk about objects and structs soon, so I'll definitely do some research.


4) Exactly. A good point. We deallocate arrays to avoid memory leaks which can be checked using valgrind. Also setting the array afterward to nullptr is helpful too.

Now there is something confusing:
I thought I only have to use delete [ ] (deallocation) only for arrays of struct. Why should this also be done for the simple arrays which are created in the system? like:
 
string*array = new string [25];


5) That is a good approach, I was also thinking about creating another int capacity in our struct. And having an if statement in our function to check:

1
2
3
4
if (arr.size > arr.capacity){
     arr.capacity = arr.capacity *2;
     arr.size = arr.capacity;     // Is this possible ? 
}

As we can see in the above code, whenever the user adds a new string element to the array, the size automatically increases and undergoes check using the if statement, and whenever the condition is met, the size is increased to twice the capacity.
Last edited on
closed account (48T7M4Gy)
Setting the array pointer to nullptr after deleting is not necessary.

If there is only one instance of the type described in the struct then it's array property must be explicitly deleted to correspond to the new. It doesn't happen automatically. So if you have an array of objects created using new, they must be separately deleted to correspond to that new. There is no magic because they are two completely separate and unrelated operations.

If you want to increase the array size, it's not that simple. You have to create a new array of the larger size and copy across the old values essentially, then delete the old array. It is not that easy and fraught with errors. This is one of the reasons <vector>'s are the way to go instead of C-style arrays.


Last edited on
I see, ok.

ok so creating the array of struct and the array of object both need to be deleted separately.

Exactly, my teacher taught me that as well. Using a for loop you can copy and send the origianl array elements into a new, one and delete the original array and then resize and pass back the elements from the temporary array, and then delete.


Thanks a lot for your help. Now I know what to do :)
Topic archived. No new replies allowed.