-1

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 ?

Muds
  • 4,006
  • 5
  • 31
  • 53
Constantin
  • 19
  • 1
  • 2
  • What is your question? – unwind Apr 14 '15 at 10:27
  • 1
    It is not clear what you are asking, please write your questions as elaborative as possible. – Muds Apr 14 '15 at 10:27
  • When I try to built this code, the compiler show me this: 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. So I can't to compile this code. What's the problem? Thank you – Constantin Apr 14 '15 at 10:29

2 Answers2

2

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;
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
nkb
  • 21
  • 2
  • Do not cast the result of `malloc` in C. – Spikatrix Apr 14 '15 at 11:31
  • In all fairness, while it is a good observation, it is not what the OP asked :P Maybe you made him miss an important lesson: that *making a program compile* does not automatically equal to having it do what he want. – Jongware Apr 14 '15 at 13:18
  • @Jongware, well to me it looked like OP wanted to get "Home is good" converted to the upper case, something like "HOME IS GOOD", and this would happen with the convertire() posted above. So both the purposes are accomplished here, program compiles and provides desired result. – nkb Apr 15 '15 at 11:07
  • @CoolGuy You would be surprised to learn how often it is used. – nkb Apr 21 '15 at 09:52
1
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.

Gopi
  • 19,784
  • 4
  • 24
  • 36