Re: memory access error in some simple code :)

From: Artie Gold (artiegold_at_austin.rr.com)
Date: 07/16/04


Date: Fri, 16 Jul 2004 12:27:09 -0500

Pavel Sorokin wrote:
> Hello,
>
> This is probably a very dumb question, but I don't understand what's
> the problem with the following code. It gives a memory access
> violation on the marked line. I'm using VC++ 7.1.
>
> void reverse(char* str, int start, int end)
> {
> for(int i=start; i<(start+end)/2; i++)
> {
> char buf = str[i];
> int endIndex = end-i;
> str[i] = str[endIndex]; // <-- this causes an error
> str[endIndex] = buf;
> }
> }
>
The code itself -- while it could be improved -- is fine. The problem
(he said, turning up the sensitivity of his crystal ball) is the way
you're calling the function.

No doubt you're doing something like:

   char * something = "reverse me";
   reverse(something);

In this case you're trying to alter the value of a string literal (which
should more properly be defined as a `const char *') which is not
permissable.

HTH,
--ag

-- 
Artie Gold -- Austin, Texas
"What they accuse you of -- is what they have planned."


Relevant Pages

  • Re: Another Understanding Pointers Question
    ... > string functions to test. ... but I just wanted to test writing my own functions. ... > int main ... Sorry if thats a dumb question.. ...
    (comp.lang.c)
  • Re: array allocaton size
    ... > This may be a dumb question, but I've searched the FAQ ... > int x; ... Some compiler-/OS-specific dynamic memory allocation information ...
    (comp.lang.cpp)
  • array allocaton size
    ... This may be a dumb question, but I've searched the FAQ ...
    (comp.lang.cpp)
  • memory access error in some simple code :)
    ... This is probably a very dumb question, ... It gives a memory access ... violation on the marked line. ... void reverse(char* str, int start, int end) ...
    (comp.lang.cpp)