The continuous problem of two dimensional pointer dynamic allocation of memory is deeply analyzed

  • 2020-04-02 01:08:20
  • OfStack

First, the site posts the test code:

#include <cstdlib>
#include <iostream>
using namespace std;
#define nWidth  3
#define nHeight 4
//Memory is allocated continuously
int main(int argc, char *argv[])
{
    int **p = NULL;
    p = (int**)malloc(nWidth*sizeof(int*));
    if(p == NULL)
    return -1;

 cout<<" Discontinuous allocation of memory: "<<endl;
    for(int j = 0; j< nWidth; j++)
    {
       p[j] = (int*)malloc(nHeight*sizeof(int));
       if(p[j] == NULL)
       return -1;
    }

    for(int i = 0; i < nWidth; i++)
  for(int j = 0; j < nHeight; j++)
  {
   printf("%p  ",&p[i][j]);
   if(j == nHeight-1)
    cout<<endl;
  }
    cout<<endl;

    for(int j = 0; j < nWidth; j++)
    {
       free(p[j]);
       p[j] = NULL;        
    }
    free(p);
    p = NULL;

    
 int **q = NULL;
    q = (int**)malloc(nWidth*sizeof(int*));
    if(q == NULL)
    return -1;

 cout<<" Continuous allocation of memory: "<<endl;
    q[0] = (int*)malloc(nWidth*nHeight*sizeof(int));
    if(q[0] == NULL)
    {
        free(q);
        return -1;
    }
    for(int i = 1;i < nWidth; i++)
    q[i] = q[i-1] + nHeight;

    for(int i = 0; i < nWidth; i++)
  for(int j = 0; j < nHeight; j++)
  {
   printf("%p  ",&q[i][j]);
   if(j == nHeight-1)
    cout<<endl;
  }
    cout<<endl;

    free(q[0]);
    q[0] = NULL;
    free(q);
    q = NULL;

    system("PAUSE");
    return EXIT_SUCCESS;
}

The running screenshot is as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201307/201307111038545.png ">

As shown in the figure, both methods of allocating memory correctly allocate memory, but memory allocation space is really different.
Analysis:
The first distribution method:
First, we allocate each row, that is, each row in nWidth, so we can see that each row is contiguous, and each row takes up four bytes
However, when allocating memory for nHeight, memory is allocated randomly, so the location of the memory is uncertain, so the first case occurs

The second distribution method:
First, again, p is allocated, and now p points to a location
However, in the second sentence, we need to note that all the required memory is allocated directly at p[0], so it is all allocated at this time, and since the memory is allocated at one time, the memory address must be continuous, the running results also prove this

There are two ways to free memory:
In the first case, since there are two different allocations of memory, we should choose different regions to release the memory.
In the second case, you just call malloc twice in a row   , so you only need to call free twice in a row to complete the release.


Related articles: