Issue
Edit: The problem was that I was not allocating memory for '\0' character.
Basically, I am having core dumped and corrupted top size errors while trying to run this code, not used to malloc and dynamic memory. My goal here is to concatenate two strings and use an allocated memory to do so. The first 'if' will concatenate only the not NULL strings, if both are regular strings, it will measure the length and allocate memory for it. The code compiles but the error happens when executing it
int str_length(const char *str){
int i=0;
if(str == NULL) return (-1);
while( *(str+i) != '\0') i++;
return i;
}
This function I use to measure the size of arrays. I cant use common libraries
char* str_concatenate(const char *stra, const char *strb){
char *concatenate;
int i=0;
if(stra==NULL || strb == NULL){
if(stra==NULL && strb == NULL) return (concatenate = NULL);
if(strb==NULL){
concatenate = (char*) malloc( sizeof(char)* (str_length(stra) + 1) ); //se a segunda e NULL, copia a primeira
do{
concatenate[i]=stra[i];
i++;
}while(stra[i]!='\0');
return concatenate;
}
else{
concatenate = (char*) malloc( sizeof(char)* (str_length(strb) + 1) ); //primeira NULL copia a segunda
do{
concatenate[i]=strb[i];
i++;
}while(strb[i]!='\0');
return concatenate;
}
}
int size_a = str_length(stra);
int size_b = str_length(strb);
int total = size_a + size_b;
concatenate = (char*) malloc( sizeof(char)*(total + 1) );
while(strb[i]!='\0'){
concatenate[size_b+i] = strb[size_b+i];
i++;
}
i=0;
while(stra[i]!='\0'){
concatenate[i] = stra[i];
i++;
}
return concatenate;
}
int main(){
char stra[] "first string"
char strb[] "second string"
str_concatenate(stra, strb);
return 0;
}
Solution
Note that you are resetting i
so essentially you are overwriting concatenate
in the second while
, you should try using a different variable to keep track of the index of concatenate
, for instance:
//...
// size of char is always 1 byte, no need to include in malloc
concatenate = malloc(total + 1); // don't forget the null byte
i = 0;
while (strb[i] != '\0')
{
concatenate[i] = strb[i];
i++;
}
int j = 0;
while (stra[j] != '\0')
{
concatenate[i] = stra[j];
i++;
j++;
}
concatenate[i] = 0; // null terminate the string, the same goes for the others
//...
Answered By - anastaciu Answer Checked By - Dawn Plyler (WPSolving Volunteer)