How do I fix Access violation writing exception

6.6k Views Asked by At

I have following bit of code

#include <stdio.h>
#include<conio.h>
#include <ctype.h>
char *convertire(char *sir)
{
    char *sir2="";
    while (*sir)
    {
        *sir2 = toupper(*sir);
        sir++;
    }
    return (sir2);
}
void main(void)
{
    char *sir = "Home is good";
    char *sir2 = convertire(sir);
    printf("Sirul obtinut este : %s\n", sir2);
    _getch();
}

When I try to compile I get the following error

First-chance exception at 0x00E3141B in pointeri.exe: 0xC0000005: Access violation writing location 0x00E35858. If there is a handler for this exception, the program may be safely continued.

Can you please help me resolve this ?

2

There are 2 best solutions below

3
Gopi On
char *sir2="";

There is no enough memory allocated for your pointer sir2 and is also just read-only.

You need something like

char *sir2 = malloc(strlen(sir1) + 1);

Accessing unallocated memory leads to undefined behavior and might cause crash. This can't be handled in any other way other than allocating memory for your pointer.

4
nkb On

You will also need to track the start of sir2, basically you would need to modify convertire() like this:

char *convertire(char *sir)
{   
    char *p;
    char *sir2=(char *)malloc(strlen(sir)+1);
    p = sir2;
    while (*sir)
      {   
        *sir2++ = toupper(*sir++);
      }
    return p;
}