C toLowerCase function not working - access violation

I have a simple function that takes an array of characters as an argument and converts all characters to lowercase. However, I get a strange access violation error. Here is the code:

void toLower(char *rec)
{
 int i=0;
 while (rec[i]!='\0')
 {
  if (rec[i]>='A' && rec[i]<='Z') 
               rec[i]='a'+rec[i]-'A';  //this is where I get an error - assigning the
                                       //the value to rec[i] is the problem
  i++;
 }
}

Can you tell me what is my mistake? Thanks

+3
source share
4 answers

In a comment, you say that you pass functions to a literal string, for example:

palindrome("In girum imus nocte et consumimur igni")

where palindromepasses its argument toLower. This will not work because string literals are read-only and you are trying to modify it. Instead, you can use:

char str[] = "In girum imus nocte et consumimur igni";
palindrome(str);

palindrome toLower.

+6

:)

#include <algorithm> //For std::transform
#include <cctype> //For std::tolower
#include <cstring> //For std::strlen

void toLower(char *rec)
{
    std::transform(rec, rec + std::strlen(rec), rec, std::tolower);
}
+6

Are you passing (even indirectly) a string literal? If so, then it can be loaded into inaccessible memory; You will need to make changes to the copy.

The fact that your function prototype accepts char *, but does not const char *, suggests that you probably did not, but I thought I would throw it away.

+6
source

It looks like you did not pass in a valid buffer. But do not write it yourself; use something like strlwr .

+1
source

Source: https://habr.com/ru/post/1741094/


All Articles