Hi everyone,
i have been trying to make a function that receives a string if the form of characters and dynamically allocates memory for every subsequent character, the function itself works fine, as long as i try to do it for only one variable (char * type), when i try to use twice(for two variables) it corrupts them both and gives a memory error
using visual studio 2008 or 2010
Code:#include <stdio.h> #include <conio.h> #include <stdlib.h> void string_realloc(char* str); int main() { /*dynalloc_req1*/char *str; char *str2; /*dynalloc_req2*/ str=(char*)malloc(2); str2=(char*)malloc(2); if(str==NULL) {printf("strfail");getch();return 0;} if(str2==NULL) {printf("str2fail");getch();return 0;} printf("Enter a string to compress: \n"); string_realloc(str); printf("Enter a string to compress: \n"); string_realloc(str2); printf("%s",str); printf("%s",str2); free(str); free(str2); getch(); return 0; } void string_realloc(char* str) { int i; //string index counter char c; //temp storage for input char for(i=0;(c=getchar())!='\n';i++) //stop condition is user "enter" { str[i]=c; if ((str=(char*)realloc(str,i+2))==NULL) {//alloc fail msg printf("\n\nallocation failed, not enough memory"); free(str); return; } } str[i]='\0';//close the string }