-1

I have following code.

1 #include <stdio.h>
2 #include <string.h>
3 
4 void encryptString2(char *encryptedString)
5 {
6   
7   while (*encryptedString)
8   {   
9       *encryptedString = *encryptedString ^ 31;
10      printf("Encrypted Character : %c\n", *encryptedString);
11      encryptedString++;  
12  }
13}
14
15 int main(int argc, char* argv[])
16 {
17  char *inputString = "Nahid";
18  printf("Input string : %s\n", inputString);
19  encryptString2(inputString);
20  printf("Input String : %s\n", inputString);
21 }

when i compile in visual studio line 9 causes problem. It shows

Unhandled exception at 0x000B1AA4 in Page_182.exe: 0xC0000005: Access violation writing location 0x000B5C40.

Can anybody explain why this error occurs and how to solve the problem? Thanks in advance.

Matt
  • 74,352
  • 26
  • 153
  • 180
nahid
  • 81
  • 10

1 Answers1

2

String literals may not be modified. Any attempt to modify a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

Instead use a character array. For example

char inputString[] = "Nahid";
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335