hi all,
i have written a simple prog tht reads user's input as string and allocates memory as and when a char is read. can anyone tell me why re-alloc fails when i execute thi below code. thanks in advance.
Code:#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void readStr(char **str1); void printStr(char **str1); void freeStr(char **str1); int main(void) { char *str1 = NULL; printf("Enter a string: "); str1 = (char *)malloc(sizeof(char)); if(str1 == NULL) { printf("Malloc failed for str1!\n"); return 1; } readStr(&str1); printStr(&str1); freeStr(&str1); return 0; } void readStr(char **str1) { char ch; int i = 0; while( (ch = getchar()) != '\n' ) { *str1[i++] = ch; if( (str1 = (char **)realloc(str1, (i+1) * sizeof(char))) == NULL ) { printf("Re-alloc failed for str1!\n"); exit(0); } } *str1[i] = '\0'; return; } void printStr(char **str1) { printf("String2 is %s\n", **str1); return; } void freeStr(char **str1) { free(str1); return; }



LinkBack URL
About LinkBacks


