user11014039
user11014039

Reputation:

Access violation writing location 0x0133585B Error

I am working on a program in C and the following function takes in three parameters and will replace a character in a string with another character. Well most of it works just fine but i get en error when trying to execute this portion of code : str[pos] = ch;. Error says "Access violation writing location 0x0133585B."

void kstrput(char *str, size_t pos, char ch)
{
    if(pos > strlen(str))
    {
        abort();
    }
    str[pos] = ch;
}

Portion of main:

char *kstr = "hello";
    int pos = 3;
    char s = '\0';
    printf("\n Enter a character ");
    scanf("%c", &s);
    kstrput(kstr,pos,s); // calling the kstrput function
    printf("\n After kstrput: %s",kstr); //printing the struct to check value of the string

Upvotes: 0

Views: 52

Answers (3)

bruno
bruno

Reputation: 32586

"Access violation writing location 0x0133585B."

you do

{
  int pos = 3;
  ...
  char *kstr = "hello";
  ...
  kstrput(kstr,pos,s); // calling the kstrput function
}

void kstrput(char *str, size_t pos, char ch)
{
   str[pos] = ch;
   ...
}

in str[pos] = ch; pos valuing 3 is a valid index but str is the string literal "hello", a string literal cannot be modified

Upvotes: 1

Loc Tran
Loc Tran

Reputation: 1180

This line in function void kstrput(char *str, size_t pos, char ch)

if(pos > strlen(str))

should be replaced by

if(pos >= strlen(str))

Upvotes: 0

Alex Lop.
Alex Lop.

Reputation: 6875

"hello" is constant (not modifiable) and might be (and probably is) stored in a read only memory.

The proper way to point to it is by using pointer of type const char *. What you need to do in your case is to define array of char and initialize it to "hello":

char kstr[] = "hello";

Also note that in kstrput if pos is equal to strlen(str) then it will override the '\0' which indicates the end of string. Better use:

if(pos >= strlen(str))

Upvotes: 2

Related Questions