Making a program that implements functions that work with arrays

Viewed 59

Doing an assignment where I have to implement some functions. One of those functions is to check if a string is a palindrome.

#include <stdio.h>
#include <stdlib.h>

char string[] = "cameron";
char string2[] = "mah";
char palindrome[] = "madam";
char notPalindrome[] = "music";

int removeChar(char *str1, char * str2, char c){
   int length = 0;
   for (int i = 0; str1[i] != '\0'; i++){
        length++;
   }
   for (int i = 0; i <= length; i++){
      if (str1[i] == c){
         str2[i] = '*';
      }
      else {
         str2[i] = str1[i];
      }
   }
   for (int i = 0; i<= length; i++){
    printf("%c", str2[i]);
   }
}

int isPalindrome(char *str){
   int length = 0;
   for (int i = 0; str[i] != '\0'; i++){
        length++;
   }
   int j = length - 1;
   int reversible = 0;
   for (int i = 0; i < j; i++){
      if (str[i] != str[j]){
         reversible++;
         break;
    }
      j--;
   }
   if (reversible > 0){
    printf("\nString is not a palindrome\n");
   }
   else {
    printf("\nString is replaceable\n");
   }
}

int main(){
  removeChar(string, string2, 'm');
  isPalindrome(palindrome);
  return 0;
}

When I run this code it says the string is not a palindrome when it should be, but why is it that if I change isPalindrome(palindrome); to isPalindrome("madam"); it works.

Also Why is it that if I comment out //removeChar(string, string2, 'm');, isPalindrome() will work properly.

1 Answers

You have a buffer overflow. removeChar implicitly assumes that str2 is the same length as str1. So when you run this:

for (int i = 0; i <= length; i++){
      if (str1[i] == c){
         str2[i] = '*';
      }
      else {
         str2[i] = str1[i];
      }
}

with str1 being "cameron" and str2 being "mah", you go past the boundaries of str2 and into the memory where palindrome is stored. So after you run removeChar(string, string2, 'm');, the char[] that used to hold mah\0 now holds ca*e and the char[] that used to hold madam\0 now holds ron\0m\0. Obviously, "ron" is not a palindrome. Try printing the values of your strings after removeChar(string, string2, 'm'); and you should see this in action.

The only reason you're allowed to do this at all without a segmentation fault is because you're using char[] instead of char*, by the way. You might prefer to use pointers over arrays so things like this don't fail silently.

Related