1

I'm working on a project where I have to replace some char in a string. I do not understand one of the errors I see.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void replaceLetters(char *text, char original, char new_char);
 {
  for (int counter = 0; text[counter] != '\0'; counter++)
  {
    if (text[counter] == original)//Error occurs here
    {
      text[counter] = new_char;
    }
    printf("%c", chr[counter]);
    }
  return 0;
}

int main()
{
  char *text = "HallO";
  char original = 'O';
  char new_char = 'N';

  replaceLetters(text, original, new_char);

  return 0;
}

At the if statement the following error occurs: thread 1 exc_bad_access (code=1 address=0x0). What does this mean, and how can I address it?

ryyker
  • 22,849
  • 3
  • 43
  • 87
Jan
  • 11
  • 3
  • 2
    `text` points to a string literal and you can't write to string literals. Change to `char text[] = "HallO";` – kaylum Nov 18 '20 at 20:08
  • Does this answer your question? [Why do I get a segmentation fault when writing to a "char \*s" initialized with a string literal, but not "char s\[\]"?](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-char-s-initialized-with-a) – kaylum Nov 18 '20 at 20:10
  • That is *not* your code because *that* code will not compile, due to the use of the non-existent `chr[]`. – paxdiablo Nov 18 '20 at 20:18

2 Answers2

3

In c, string literals like "HallO" are stored in global read-only memory. If you want to modify the string, you will need to keep it in a buffer on the stack.

  char text[6] = "HallO";
mCoding
  • 4,059
  • 1
  • 5
  • 11
  • 3
    As an aside, you're often better off using `char text[] = ...` so you don't have to work out the size. – paxdiablo Nov 18 '20 at 20:19
0

"What does this mean, and how can I address it?"

It is an access violation. The string you have defined

char *text = "HallO";  

is referred to in C as a string literal, and is created in an area of read-only memory, resulting in an access violation.

This can be easily addressed by creating the original variable such that it is editable. eg:

char text[6] = "HallO"; //okay
char text[] = "HallO"; //better, let the compiler do the computation
char text[100] = "HallO"; //useful if you know changes to string will require more room
ryyker
  • 22,849
  • 3
  • 43
  • 87