i wrote this function, which read strings char by char and increase the allocated size. for some reason im getting randomly the error " _CrtIsValidHeapPointer" in VS2010, while reading strings with around 100+ chars. i tried to debug it, but i really cant figure whats wrong
char *unknown_size_string(){
int i=0, size=10;
char *name=NULL, *alloc_check=NULL, letter;
//allocates initial size of 10 bytes
name=(char *)malloc(sizeof(char)*size);
if(!name){return NULL;}
//reads char by char until newline reached
while((letter=getchar())!='\n'){
*((name)+i++)=letter;
//when the remaining buffer size is 1 byte, allocating another 10 bytes
if((i+1)==size){
alloc_check=name;
realloc(alloc_check,(size+=10)*sizeof(char));
if(!alloc_check){return name;}
name=alloc_check;
}
}
*((name)+i)='\0';
return name;
}
any help would be appreciated.
thanks
*((name)+i='\0';could result in an error if string had exact length of 10 chars, you will not realloc it, then add '\0' at the eleventh position (i = 10)... Or maybe I'm wronggetline, which does what you're trying to do, but probably more efficiently. Note that this function is not part of the base standard, but of an extension. Read the linked reference page for more details.