In this example i want to learn how to dynamically allocate the memory. This is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int n = 0;
char a[]="asd";
n = sizeof(a)/sizeof(char);
printf("\n %i \n\n",n);
char *corner;
corner = (char *)malloc(sizeof(char)*n);
strcpy(corner, a);
printf("\n %s \n\n",corner);
free(corner);
char b[]="asdddddddd";
n = sizeof(b)/sizeof(char);
corner = (char *)malloc(sizeof(char)*n);
strcpy(corner, b);
printf("\n %s \n\n",corner);
int x = sizeof(corner)/sizeof(corner[0]);
printf("\n %i \n\n",x);
return 0;
}
The result of this code is :
4
asd
asdddddddd
4
So I dont know how to use malloc and free properly. First part of code is clear for me. First i am measuring lenght of array a
, then i am creating pointer to the same lenght of memory as array a
uses, next i am copying array a to another place in memory pointed by *corner
.
After printing string of characters I want to reuse corner
, so i am freeing the memory and try to define the new lenght of array because i want to store other (longer or shorter) string. I dont know why, "new" corner
is printing properly but when i am checking it lenght it shows me 4 again. Why? Is corner
only 4 chars long? How to recreate corner with proper lenght? I know that this part of code makes no sense but this is only for traning.