S
sanjaymeher
Hi,
Right now addDynamicMemory(char **ptr, int size) method can able to
handle if input ptr is intitialized to NULL or something. But how to
improve this method to handle uninitialized pointed even. Any Answer ??
Thanks,
Sanjay
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int addDynamicMemory(char **ptr, int size)
{
/* See and chek whether size memory is available or not */
int currSize;
if(*ptr == NULL)
{
*ptr = (char*) malloc(size * sizeof(char));
if(ptr == NULL)
{
printf("Initialized memory as null \n");
return -1;
}
else
{
printf("Can not Initialized memory as null \n");
return -1;
}
}
currSize = strlen(*ptr);
size = currSize + size;
*ptr = (char*) realloc(*ptr, size*sizeof(char));
if(ptr != NULL)
{
printf(" re Allocation size is %d\n",size);
return 0;
}
printf(" re Allocation failed \n");
return -1;
}
//int main(int argc, char* argv[])
void main()
{
char *test;
test = NULL;
addDynamicMemory(&test, 40);
printf("At first test value is %s\n",test);
strcpy(test,"444444444");
printf("After allocation val is %s\n", test);
addDynamicMemory(&test, 50);
strcat(test,"5555555555");
printf("After allocation val is %s\n", test);
}
Right now addDynamicMemory(char **ptr, int size) method can able to
handle if input ptr is intitialized to NULL or something. But how to
improve this method to handle uninitialized pointed even. Any Answer ??
Thanks,
Sanjay
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int addDynamicMemory(char **ptr, int size)
{
/* See and chek whether size memory is available or not */
int currSize;
if(*ptr == NULL)
{
*ptr = (char*) malloc(size * sizeof(char));
if(ptr == NULL)
{
printf("Initialized memory as null \n");
return -1;
}
else
{
printf("Can not Initialized memory as null \n");
return -1;
}
}
currSize = strlen(*ptr);
size = currSize + size;
*ptr = (char*) realloc(*ptr, size*sizeof(char));
if(ptr != NULL)
{
printf(" re Allocation size is %d\n",size);
return 0;
}
printf(" re Allocation failed \n");
return -1;
}
//int main(int argc, char* argv[])
void main()
{
char *test;
test = NULL;
addDynamicMemory(&test, 40);
printf("At first test value is %s\n",test);
strcpy(test,"444444444");
printf("After allocation val is %s\n", test);
addDynamicMemory(&test, 50);
strcat(test,"5555555555");
printf("After allocation val is %s\n", test);
}