dynamic memory allocation (C programming)

advertisements

I am learning about dynamic memory allocation and having a problem while doing the exercise. I would like to allocate the memory for p. The following is the codes.

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    int *p, i;

    p = (int *)malloc(7 * sizeof(int));
    if (p == NULL)
    {
        printf("Memory Allocation Errors\n");
        exit(1);
    }
    for(i=0; i<6; i++)
    {
        p++;
        *p = i;
        printf("%3d",*p);
    }
    printf("\n");
    p = p - 6;
    free(p);
    p = NULL;
    return 0;
}

The running result is:0 1 2 3 4 5

However, when I change the code

p = (int *)malloc(7 * sizeof(int));

to this

p = (int *)malloc(6 * sizeof(int));

the running result would be

0  1  2  3  4  5
Error in `./memo2': free(): invalid next size (fast): 0x0000000001bc5010 ***
Aborted (core dumped)

I think for this code, p only need the memory of the size of 6 integers, could anyone give a explanation?

Another question is that why should p++ be ahead of *p = i? If I make *p = i before p++, the running result would be 0 0 0 0 0 0.


First question - you get an error when you malloc memory for 6 integers because in your for loop you increment the pointer before assigning a value. Therefore you leave the first address you allocated empty. If you assign a value and then increment the pointer this will solve your problem.

Second question - if you perform the printf after incrementing the pointer you won't print the value you just set. You need to assign the value, print it, then increment the pointer.

Here's your code with those changes:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
   int *p, i;

   p = (int *)malloc(6 * sizeof(int));
   if (p == NULL)
   {
      printf("Memory Allocation Errors\n");
      exit(1);
   }
   for(i=0; i<6; i++)
   {
      *p = i;
      printf("%3d",*p);
      p++;
   }
   printf("\n");
   p = p - 6;
   free(p);
   p = NULL;
   return 0;
}

However, I would recommend you use array indexing syntax. As well as being easier to read, this means that you don't actually change the p meaning that when you free the memory it will be on the correct address. Here's an updated version of your code using array indexing:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
   int *p, i;

   p = (int *)malloc(6 * sizeof(int));
   if (p == NULL)
   {
      printf("Memory Allocation Errors\n");
      exit(1);
   }
   for(i=0; i<6; i++)
   {
      p[i] = i;
      printf("%3d",p[i]);
   }
   printf("\n");
   free(p);
   p = NULL;
   return 0;
}