Deleting a structure

Jan 31, 2013 at 11:48pm
So i have this structure:

1
2
struct contrib {int num; string name; string adress;};
typedef contrib *cont;


and i was wondering how do i free all the memory that one object of this type ocupies. Does this work:

1
2
3
void erasecont (cont ct){
    delete[] ct;
}


does it only delete the pointer or it also deletes the int and the strings?

thank you
Jan 31, 2013 at 11:56pm
If I'm right in saying this, you haven't used the new keyword. So there's nothing to delete.

If you create and 'object' of this struct within a function, then the memory will be freed when it goes out of scope. i.e. the function it was created in ends.
Feb 1, 2013 at 12:11am
Right, i have this function to create a cont:

1
2
3
4
5
6
7
8
9
10
11
12
cont createcont ()
{cont rcont = new contrib;
string n;

cout << "Name: ";
getline (cin,rcont->name);
cout << "\nNumber: ";
getline (cin, n);
stringstream(n) >> rcont->num;
cout << "\nAdress: ";
getline (cin,rcont->adress);
return rcont;}


so the new is used. and i want the function erasecont to delete everything that was created by this function (i hope i am explaining myself well, i just want to free memory).
Feb 1, 2013 at 12:34am
Again, I'm not to sure. But the following compiles and runs for me.
Sorry, I usually deal with deleting 'new' within the same functions!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int *testFunc()
{
	int *me = new int;

	*me = 5;

	return me;
}

void eraseMe( int *value )
{
	delete value;
}

int main()
{
	int *meCopy = testFunc();    

	eraseMe( meCopy );     

	return 0;
}


Hopefully someone with more knowledge will see this thread, lol.
I'd also like to know if this is actually deleting the memory taken by 'new' in the above function.
Feb 1, 2013 at 10:19am
delete[] is usually used for deleating arrays. For single objects only use delete.
You create your item as cont rcont = new contrib
if you would create it using cont rcont = new contrib[x]; then you would use delete[];

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

struct contrib {int num; string name; string adress;};


int main()
{
  contrib *pCon = new contrib[5];
  contrib *pCon2 = new contrib; 
  delete[] pCon;
  delete pCon2;

  return 0;
}
Feb 2, 2013 at 3:32am
so that would delete the pointer *pCon2 and get rid of it's num, name and adress?
Feb 2, 2013 at 10:45am
Yes, they are considered as just one single object by the compiler.
Feb 2, 2013 at 5:28pm
Thank you for the help!
Topic archived. No new replies allowed.