Hi Guru's, Below find function to replace string, this function is called using an ETL application and replaces the string and was working fine for low volumes() but if volumes are big it errors out with Heap allocation failure, Can you someone suggest what I've missed or need to avoid or Is there a better way to do so. Code: #include <stdio.h> #include <string.h> #include <stdlib.h> char* pxStringReplace(char *str, char *subStr, char *rep, int num) { char *result =(char *)malloc(sizeof(char) * (strlen(str) + 1)); int newlen = strlen(rep); int oldlen = strlen(subStr); int i = 0; //replace all instances if value of num less than or equal to 0 if (num <= 0) {num = strlen(str);} while (*str) //for the complete input string { if (num != 0 ) // untill no more occurances need to be changed { if (strstr(str, subStr) == str ) { strcpy(&result[i], rep); i += newlen; str += oldlen; num--; } else // if no match is found { result[i++] = *str++; } } else { result[i++] = *str++; } } result[i] = '\0'; //Terminate the string return result; //Return the replaced string free(result); //free memory } Thanks All for reading. Regards....
The problem is most likely the last line of that function. You can not put any executable code after that return statement. And besides, what good is it to free the pointer before the calling function has a chance to use it? It is the calling function's responsibility to free the memory for that pointer after it is done with it. Code: void foo() { char* p = pxStringReplace( /* put parameters here */); // do something with p printf("%s\n", p); // after done using p, you have to free it up free(p); }
What exactly is that function supposed to do? Replace one substring with another? such as replace "John" with "Henry"? What to do when the new substring is not the same length as the old one? It would seem that variable result is not being allocated anough space to hold the potentially expanded string. One thing you can try is to increase the amount of memory malloc()'ed at the beginning of that function. char *result = malloc((strlen(str) + 32)); Two things to note here: (1) C language does not need typecasting void* returns. (2) sizeof(char) is guarendeed by c standard to be 1. So multiplying something by sizeof(char) is the same as multiplying something by 1. Both are useless statements. If adding the additional bytes to the result doesn't fix the problem then write a small program that illustrates the problem and post it here so that we can test it. Also don't forget to post the test data you are using.