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.
malloc. Secondly of all, you don't initialize the first item in the allocated memory. Thirdly, wouldn't it be much easier to either use array-indexing syntax instead of pointer arithmetic, or to have two pointers, one original that you pass tofreeand one that you do whatever arithmetic you want?p++;move to afterprintf("%3d",*p);