0
votes

I have a problem with my program in C++. I have a template class which have a function bool that checks if the given word or array is a palindrome. For int and char everythig is fine, and program generate "yes", but for string program starts but it gives

First-chance exception at 0x534408DA (msvcr120d.dll) in PK4_5.exe: 0xC0000005: Access violation reading location 0x00000003. Unhandled exception at 0x534408DA (msvcr120d.dll) in PK4_5.exe: 0xC0000005: Access violation reading location 0x00000003.

What is wrong in this code?

Here is the code:

main function:

#include "palindrom.h"
int main(){
    int iTab[] = { 1, 2, 3, 2, 1 };
    char cTab[] = "abcba";
    string word ("aaaa");

    palindrom<int> A;
    palindrom<char> B;
    palindrom<string> C;
    if (A.palindrome(iTab, 5))
        cout << "yes";
    if (B.palindrome(cTab, strlen(cTab)))
        cout << "yes";
    if (C.palindrome(&word, word.length()))
        cout << "yes";
    return 0;
}

palindrom.h:

#pragma once
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class palindrom
{
public:
    bool palindrome(const T*x, int length);
    palindrom();
    ~palindrom();
};

template <typename T>
bool palindrom<T>::palindrome(const T* x, int length){
    for (int i = length / 2 - 1; i >= 0; i--)
    if (x[i] != x[length - i - 1])
            return false;
        return true;
}

template <typename T>
palindrom<T>::palindrom(){}
template <typename T>
palindrom<T>::~palindrom(){}

palindrom.cpp is empty.

2
Time to learn how to compile with debug info and how to use your debugger. - Basile Starynkevitch
should have done waaay before learning templates. this is just weird. - Karoly Horvath

2 Answers

2
votes

The problem is that you pass the collection you want to create palindrome from as a pointer. That means, from the std::string you treat it as an array of strings, so doing anything else than x[0] will cause undefined behavior.

Instead pass it as a non-pointer, and create the palindrom with a pointer template type when needed:

palindrom<int*> A;
palindrom<char*> B;
palindrom<string> C;

This way, you can have

bool palindrome(const T& x, int length);

and it will work for std::string as well.

0
votes

Change if (C.palindrome(&word, word.length())) to if (C.palindrome(word.c_str(), word.length())).

Also, don't put using namespace std; in your header file, otherwise everything that includes your header file will import the namespace std, which may not be desired behaviour.