Functions to allocate and de-allocate memory.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • darkdai
    New Member
    • May 2010
    • 1

    Functions to allocate and de-allocate memory.

    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
    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");
    
    	}
    }
    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.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Try printing out the value of the pointer in all parts of your program, allocate, after calling main in allocate and in reallocate and see what you see, then answer

    How does allocate pass the pointer back to main?

    Comment

    Working...