Currently learning memory management in C, and I am currently running into issues increasing string length as a loop iterates.
The method I am trying to figure out logically works like this:
// return string with "X" removed
char * notX(char * string){
result = "";
if(for int = 0; i < strlen(string); i++){
if (string[i] != 'X') {
result += string[i];
}
}
return result;
}
Simple enough to do in other languages, but managing the memory in C makes it a bit challenging. Difficulties I run into is when I use malloc and realloc to initialize and change size of my string. In my code I currently tried:
char * notX(char * string){
char* res = malloc(sizeof(char*)); // allocate memory for string of size 1;
res = ""; // attempted to initialize the string. Fairly certain this is incorrect
char tmp[2]; // temporary string to hold value to be concatenated
if(for int = 0; i < strlen(string); i++){
if (string[i] != 'X') {
res = realloc(res, sizeof(res) + sizeof(char*)); // reallocate res and increasing its size by 1 character
tmp[0] = string[i];
tmp[1] = '\0';
strcat(res, tmp);
}
}
return result;
}
Note, I have found success in initializing result to be some large array like:
char res[100];
However, I would like to learn how to address this issue with out initializing an array with a fixed size since that might potentially be wasted memory space, or not enough memory.
malloc(sizeof(char*))= allocating the size of a pointer. Further,realloc(res, sizeof(res) + sizeof(char*));reallocates to the size of two pointers always. I don't think you understand howsizeofworks. Andres = "";causes two catastrophes. (1) it leaks the memory allocated just one line prior, and (2) it now causesresto point to a constant string, i.e. memory no longer dynamically managed, therefore passing it toreallocinvokes undefined behavior.len +1characters. At the end of the loop you could decide to realloc() it.strlen(string)every single iteration, even though it is constant. As is, you wouldn't even need to know the length since you could just iterate until you hit the NUL terminator. Likewise repeatedstrcatgets increasingly ineffective since it needs to find the end of the string every time. Rather keep track of the end position and append there. (Note that these are more long-term things to consider and ways of thinking in general, first learn how memory allocation, pointers andsizeofwork, and the difference between arrays and pointers.)