Bhupesh Pant
Bhupesh Pant

Reputation: 4329

using strstr() function is breaking

I am using strstr() function but I am getting the crash.

This part of code is crashing with error "Access violation reading location 0x0000006c." strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))

Here is the complete code...

#include "stdafx.h"    
#include <iostream>
#include <string>
void delchar(char* p_czInputString, const char* p_czCharactersToDelete)
{
    for (size_t index = 0; index < strlen(p_czInputString); ++index)
    {
        if(NULL != strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))
        {
            printf_s("%c",p_czInputString[index]);

        }
    }
}
int main(int argc, char* argv[])
{
    char c[32];
    strncpy_s(c, "life of pie", 32); 
    delchar(c, "def");

    // will output 'li o pi'
    std::cout << c << std::endl;
}

Upvotes: 0

Views: 2903

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

you are using the wrong strstr. probably you need strchr or strpbrk.

#include <cstring>
#include <algorithm>

class Include {
public:
    Include(const char *list){ m_list = list; }

    bool operator()(char ch) const
    {
        return ( strchr(m_list, ch) != NULL );
    }

private:
    const char *m_list;
};

void delchar(char* p_czInputString, const char* p_czCharactersToDelete){
    Include inc(p_czCharactersToDelete);
    char *last = std::remove_if(p_czInputString, p_czInputString + strlen(p_czInputString), inc);
    *last = '\0';
}

Upvotes: 1

Deepu
Deepu

Reputation: 7610

The prototype of strstr() is as follows,

char * strstr ( char * str1, const char * str2 );

The function is used to locate substring from a main string. It returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

In your case you are passing the wrong parameters to the strstr(). You are calling, strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]));, which is wrong. Because the pointer p_czCharactersToDelete points to the sub string constant and p_czInputString points to the main string. Call strstr() as strstr(p_czInputString, p_czCharactersToDelete); and make corresponding changes in the function delchar().

Upvotes: 2

Related Questions