+ 2
Why it's give error
Segmentation fault https://sololearn.com/compiler-playground/cCfhe0geES39/?ref=app
6 Answers
+ 3
It's better to use an array for 'hey' instead of a pointer to a string literal, as string literals should not be modified. Removed the unnecessary 'free' calls as we are not dynamically allocating memory. Simplified the printing of the modified string using 'printf'. Corrected the 'replaceAll' function to replace the 'old' string with the portion of the string after 'old'. This code snippet should work without errors and accomplish the task of replacing the specified substring in the string.
I fixed it⤾ď¸
https://sololearn.com/compiler-playground/c0A73FdRGRJT/?ref=app
+ 2
If you set str[index] = '\0', you would be truncating the str string such that it only contains elements up to the position index. Everything after index in the original string would be deleted or ignored when printing or processing the string further.
+ 1
In general I tried to see what the result
After str[index] = '\0'
What happens to string after this âď¸
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replaceAll(char *, const char*);
int main() {
char *hey = malloc(strlen("hello mf im god here punk") + 1);
strcpy(hey, "hello mf im god here punk");
const char *nee = "god";
replaceAll(hey, nee);
printf("\n%s\n", hey);
free(hey);
return 0;
}
void replaceAll(char *str, const char *old) {
char *pos = str;
size_t old_len = strlen(old);
while ((pos = strstr(pos, old)) != NULL) {
memmove(pos, pos + old_len, strlen(pos + old_len) + 1);
}
}
You should use dynamic memory allocation for hey and nee
0
replaceAll(hey, nee, ""); if you want to replace use this snippet
0
You should check out the line scanf("%d",&n); . The error can be generated by absence of '&' in your scanf line