dynamic memory allocation (C Programming) - Stack Overflow
What are good projects to get comfortable with dynamic memory and pointers in general?
what is the point of dynamic allocation in c? (plus dont get triggered. please explain why im wrong)
Dynamic memory allocation ** in stack**?
Videos
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;
}
Your code needs 7 "slots" to store 6 numbers because the very first slot is immediately skipped:
for(i=0; i<6; i++)
{
p++; // <-- Skip to next "slot"
*p = i;
printf("%3d",*p);
}
So the first slot is never used since it's immediately skipped. To fix this, first work with the current pointer, then increment it:
p = 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++; // <-- Skip to next "slot"
}
Also, the pointer you pass to free must be exactly the same pointer you got from malloc. You can calculate the original value by undoing the additions you did in a loop, but it's easier to store the original value (less chance to screw up):
int *p, *orig_p, i;
orig_p = malloc(6 * sizeof(int));
if (orig_p == NULL)
{
printf("Memory Allocation Errors\n");
exit(1);
}
p = orig_p;
...
free(orig_p);