C
C
comradegoryaev2015-02-13 11:33:21
C++ / C#
comradegoryaev, 2015-02-13 11:33:21

Why does System.AccessViolationException appear in Visual Studio 2010?

There is this code:

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
using namespace System;

void reverse (char * str, int count = 0);

int main(array<System::String ^> ^args)
{
  char * str = "Hello";
  reverse (str, 3);
  cout<<str;
    _getch();
    return 0;
}
void reverse (char * str, int count)
{
  char temp;
  if (count == 0) 
    count = strlen(str) - 1; 
  for (int i = 0, j = count; i < j; i++, j--)
  {
    temp = str[i];
    str[i] = str[j];
    str[j] = temp;
  }	
}

reverse() writes the first count characters to str in reverse order, if count is not specified or is zero, then the entire string is used. After the line "str[i] = str[j];" a System.AccessViolationException is thrown.
This is not the first version of the code for this function. In the first option, I dynamically created a char array and wrote str to it the other way around, but when I copied it back to str (via strcpy()), the same exception was thrown.
This is an example from Schildt's book "C++ Tutorial", this version is written in the book. I'm starting to think that VS is the problem.
UPD. I've also had this exception before when dealing with char arrays allocated with new in VS, although it seemed like it should work. I did not find the answer to my question on the Internet, mostly people allocated memory incorrectly, or did not allocate it at all.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Martyanov, 2015-02-13
@comradegoryaev

Try char * str = "Hello"; replace with char str[] = "Hello";
I suspect that the string "Hello" during assembly is placed in a section without write permissions, you use this pointer and try to write to the same RO area.

A
AxisPod, 2015-02-13
@AxisPod

Why is .NET here at all? Why are you creating C++/Cli projects at all if you don't need to? Why do you need a CLR project, do Win32, then it will be easier to understand you and no matter how errors you do not understand will fly out. It's hard to believe that the book you mentioned asks you to create CLR projects. And with translations into Russian, a common problem is a lot of typos.

S
Sumor, 2015-02-13
@Sumor

Error in the line
Needed
In general, a few more comments, but on the question exactly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question