zman419 zman419 - 2 months ago 12
C Question

Unhandled exception thrown: read access violation

I was doing an assignment for my C class in school and I hit a little snag.

#include <stdio.h>

char stringToUpper(char * sName )
{
while(*sName != '\0')
{
stringToUpper (* sName);
++* sName;
}
}

int main()
{
char str[50];
char * sName;
printf("Please enter your name ");
scanf("%s", str);
printf("Hello %s ", str);
sName = str;
stringToUpper(sName);
printf("Name in uppercase: %s ", sName);
}


I tried looking for other solutions already, however I found that everyone else's problems were much more advanced than the level I'm at and really just couldn't follow it. I've still a little new at working with pointers and still a little confused about how they work (only a few weeks into the class) so I feel like the issue has something to do with that. I'm almost certain that the issue has something to do with the while statement.

This is the error I get:


Unhandled exception thrown: read access violation.

sName was 0x41.

If there is a handler for this exception, the program may be safely continued.


Thanks in advanced for whatever help I receive.

Answer

Your stringToUpper function has some issues:

while(*sName != '\0')
{
    stringToUpper (* sName);
    ++* sName;
}
  • You could be calling toupper to change to upper case and assigning the value back to *sName instead of having the function call itself. In fact, the call you had is incorrect because you're passing a char to a function expecting a char *. In the next iteration of stringToUpper, it attempts to dereference that invalid pointer which causes the crash.
  • You should be incrementing sName (which points to the current character), not *sName.

The corrected version:

while(*sName != '\0')
{
    *sName=toupper(*sName);
    ++sName;
}