In my_strcat(), you used a char ** pointer while you transfer a char * pointer, maybe you can use (char *)dest.
(Also, since you have a my_strlen() function, you don't need a for loop to get the length of array.)
in this case, i tried to fix it like :
#include <stdlib.h>
#include <stdio.h>
#ifndef MY_STRING_H
#define MY_STRING_H
int my_strlen(char *str){
int count;
for (count = 0; str[count] != '\0'; ++count);
return count;
}
void my_strcat(char **dest, const char *src){
size_t srcSize = my_strlen((char *)src);
size_t destSize = my_strlen((char *)dest);
dest = realloc(dest ,(srcSize+destSize) * sizeof(char));
int count;
int count2=0;
printf("%s\n", (char *) dest); //prints null here
for (count=0 ;((char *)dest)[count]!='\0'; ++count); //throws segmentation error here
for (; src[count2] != '\0'; ++count2){
((char *)dest)[count] = src[count2];
count += 1;
}
((char *)dest)[count] += '\0';
}
int main (){
char str[80] = "these strings";
my_strcat ((char **) str,"are ");
my_strcat ((char **) str,"concatenated.");
printf("%s", str);
return 0;
}
#endif // MY_STRING_H
By chance, i noticed that if replace printf("%s\n", (char *) dest) to printf("%s \n", (char *) dest), something wrong will happen. Amazing! I tried to read assembly code to found the difference between two code, and i find that for the first printf, it will be compilered into puts while the second will be compilered into printf with "%s \n" compilered into a string. I haven't know what happened now.
Then, suddenly, i think that we transfer a pointer str which point to data in stack, while it seems we need a pointer point to data in heap.
i tried some simple code:
#include <stdlib.h>
#include <stdio.h>
int main (){
char str[80] = "these strings";
printf("%lld\n", str);
void * p = realloc(str ,100 * sizeof(char));
printf("%lld", &((char *)p)[4]);
return 0;
}
it works well.
however, in:
#include <stdlib.h>
#include <stdio.h>
int main (){
char str[80] = "these strings";
printf("%lld\n", str);
char str1[80] = "these strings";
printf("%lld\n", str1);
void * p = realloc(str ,100 * sizeof(char));
printf("%lld", &((char *)p)[4]);
return 0;
}
it can't work.
then:
#include <stdlib.h>
#include <stdio.h>
int main (){
char * str = (char *)malloc(80);
str[0] = 'h'; str[1] = 'i'; str[2] = '\0';
printf("%lld\n", str);
char str1[80] = "these strings";
printf("%lld\n", str1);
void * p = realloc(str ,100 * sizeof(char));
printf("%lld", &((char *)p)[4]);
return 0;
}
it works well.
so, it seems you can't get str by this way, for the pointer transfered into realloc() should be alloced by malloc(), calloc() or realloc(). In another word, this pointer should point to data in heap. You can see this in realloc - cppreference. When i change the way we get str by malloc, it works well. You can try this.
At last, from the args of my_strcat(), i think maybe you should change the way you implement this function.
I haven't written C code for a long time, hope this can help you.