My assignment is to write a C function void censor(char *start) that will replace all 4 letter words in the string pointed to by start with ****. Assume that words are delimited by blank chars. The beginning and the end of strings are also delimiters. I am not to use [ ] in your code. For example, the following code:
int main(){
char myStr[50] = ”this is a test for the last word in line”;
censor(myStr);
printf(”%s\n”, myStr);
}
would yield:
**** is a **** for the **** **** in ****
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* findBlank(char *start)
{ char *tempStart = start;
while(*tempStart != '\0') {
if(*tempStart == ' ') {
return tempStart;
}
tempStart++;
}
return NULL;
}
void fourStars(char *start)
{
char *tempStart = start;
for (int i = 0; i < 4; ++i) {
*tempStart = '*';
tempStart++;
}
}
void censor(char *start)
{
char *temp;
while(*start != '\0') {
int len = 0;
temp = findBlank(start);
while(start < temp && *start != '\0'){
len++;
start++;
}
if(len == 4) {
char *replace = temp - len;
fourStars(replace);
}
if ((*start != '\0') || (*(temp+1) != '\0')) {
start = temp + 1;
}
}
}
int main()
{
char myStr[50] = "this is a test for the last word in line";
censor(myStr);
printf("%s\n", myStr);
}
I tried running it through the gdb debugger and also trying to trace it but I am unable to resolve this. Here was the output from the gdb debugger:
Program received signal SIGSEGV, Segmentation fault.
0x000055555555527c in censor (start=0x1 <error: Cannot access memory at address 0x1>) at main.c:29
29 while(*start != '\0') {
I'm not allowed to change the functionality of my findBlank or fourStars functions.
Your program segfaults on while(*start != '\0')
as start == 1
. It was assigned that value from start = temp + 1
so temp == NULL
. temp
is NULL
when findBlank()
doesn't find any spaces. If you want the last 4 letter word censored then the minimal fix is for findBlank()
return a pointer to the '\0' instead of NULL:
char *findBlank2(char *start) {
for(; *start && *start != ' '; start++);
return start;
}
and example run:
**** is a **** for the **** **** in ****