Thursday, July 12, 2012

C/C++ Programming Notes 1. dynamic allocate memory

In the following example: I will show you three different way to dynamically allocate memory in run time.
1. malloc/free, which is the C style programming
2. new/delete, which is the C++ style programming
3. vector, which is the STL style programming

About which is better than the others, it is really depend on your application. However, normally speaking, if you are programming for C++, new / delete is alway recommended than malloc/free. Comparing to new/delete and vector. I would prefer vector, since the STL provide various interfaces for us to effectively manage our memory.

Example Code:


#include <iostream>
#include <vector>

using namespace std;
int main(int argc, char *argv[]) {
// dynamic alloc by using malloc/free 
int *arr_malloc;
int count = 5;
// dynamic alloc by using malloc/free
for (int i = 1; i <= count; i++){
arr_malloc = (int*)malloc(i);
for(int j = 0; j < i; j++){
arr_malloc[j] = j * 2;
}
for(int j = 0; j < i; j++){
cout << arr_malloc[j] << " ";
}
cout << endl;
}
free(arr_malloc);
// dynamic alloc by using new/delete
cout << "new/delete" << endl;
for(int i = 1; i <= count; i++){
int* arr_new = new int[i];
for(int j = 0; j < i; j++){
arr_new[j] = j * 2;
}
for (int j = 0; j < i; j++) {
cout << arr_new[j] << " ";
}
cout << endl;
delete [] arr_new;
}
// dynamics alloc by using vector
cout << "vector" << endl;
vector<int> arr_vector;
for (int i = 1; i <= count; i++) {
arr_vector.resize(i);
for(int j = 0; j < i; j++){
arr_vector[j] = j * 2;
}
for (int j = 0; j < i; j++) {
cout << arr_vector[j] << " ";
}
cout << endl;
arr_vector.clear();
}
return 0;
}

No comments:

Post a Comment

prettify