hey everyone im trying to write a code that will have different functions which will allocate memory, de-allocate, reallocate etc. this is my code
i need some help.
when i allocate memory and print the address, its always the same, is that the normal?
im supposed to free the pointer in a different function but i couldnt do it.
and my program crashes when i enter the new size i want to reallocate.
Code:
#include<stdio.h>
#include<stdlib.h>
void main()
{
void allocate(int *ptr);
void reallocate(int *ptr);
void ffr(int *ptr);
int ans=0;
int *ptr;
allocate(ptr);
reallocate(ptr);
}
void allocate(int *ptr)
{
int size;
printf("Enter the size that you want to allocate:");
scanf("%d", &size);
ptr=(int *)malloc(size*sizeof(int));
if(ptr!=NULL)
{
printf("Memory is allocated\n");
}
else
{
printf("Failed to allocate memory\n");
}
printf("The address of the allocated memory is :%u\n", &ptr);
printf("Would you like to free the memory?\n");
int choice;
printf("If yes, press 1.\n if no, press 2.\n");
scanf("%d", &choice);
if(choice==1)
{
free(ptr);
}
}
void reallocate(int *ptr)
{
int size;
printf("Enter the new size you want to allocate");
scanf("%d", &size);
ptr=(int *)realloc(ptr,size*sizeof(int));
if(ptr!=NULL) {
printf("Now allocating more memory... \n");
}
}
when i allocate memory and print the address, its always the same, is that the normal?
im supposed to free the pointer in a different function but i couldnt do it.
and my program crashes when i enter the new size i want to reallocate.
Comment