Memory access violation. What happened to this seemingly simple program?

This is a brief program that I just wrote to find out if I remember how to start a c ++ C ++ program. It just reverses the string (in place) and looks generally right for me. Why is this not working?

#include <iostream>
using namespace std;

void strReverse(char *original)
{
    char temp;
    int i;
    int j;
    for (i = 0, j = strlen(original) - 1; i < j; i++, j--)
    {
        temp = original[i];
        original[i] = original[j];
        original[j] = temp;
    }
}

void main()
{
    char *someString = "Hi there, I'm bad at this.";
    strReverse(someString);

}
+3
source share
7 answers

If you change this value, which makes the someStringpointer to a read-only literal:

char *someString = "Hi there, I'm bad at this.";

which makes a someStringmodifiable array charinitialized from a string literal:

char someString[] = "Hi there, I'm bad at this.";

You should have better results.

someString (char*) char, , ( ), - , undefined, .

+15

, ++ , , ++:

std::string s("This is easier.");
std::reverse(s.begin(), s.end());

, int main(), int main(), !

+11

- , . ( ).

, :

char *someString = "Hi there, I'm bad at this.";
char* stringCopy = new char[strlen( someString ) + 1];
strcpy( stringCopy, someString );
strReverse( stringCopy );
delete[] stringCopy;//deallocate the copy when no longer needed
+2

char *someString = "Hi there, I'm bad at this.";

someString , . :

char someString[] = "Hi there, I'm bad at this.";
+2

( ). , , - :

int main()
{
    char *str = new char[a_value];
    sprintf(str, "%s", <your string here>);
    strReverse(str);
    delete [] str;
    return 0;
}

[edit] strdup , strncpy... , :)

+1

. sharptooth.

:

#include <cstring>

void main()
{
    char someString[27];
    std::strcpy( someString, "Hi there, I'm bad at this." );
    strReverse( someString );
}

, char * <string> . ++, C.

+1

:

char* str = "Constant string";

:

const char* str = "Now correct";
const char str[] = "Also correct";

This allows you to quickly detect these errors. Or you can just use an array of characters:

char str[] = "You can write to me, but don't try to write something longer!";

To be completely safe, just use std :: string. You still use C ++, and raw string processing is very error prone.

0
source

Source: https://habr.com/ru/post/1723221/


All Articles