user1318308
user1318308

Reputation: 1

Dev C++ Access Violation (Segmentation Fault) error

i was executing this code, when i encountered an error. By executing the Debugger the error was so "An Access Violation (Segmentation Fault) error raised in you program".

/* Statcstr.cpp
* Le stringhe sono in realta' array static
*/
#pragma hdrstop
#include <condefs.h>
#include <string.h>
#include <iostream.h>
//---------------------------------------------------------------------------
#pragma argsused
int Modifica();
void Attesa(char *);
int main(int argc, char* argv[]) {
while( Modifica() );
Attesa("terminare");
return 0;
}
int Modifica() {
static unsigned int i = 0; // Per contare all'interno della stringa
char *st = "Stringa di tipo static\n";
if(i < strlen(st)) { // Conta i caratteri nella stringa
cout << st; // Stampa la stringa
st[i] = 'X'; //<--- THIS IS THE FAILING INSTRUCTION
i++; // Punta al prossimo carattere
return 1;
} else
return 0; // Indica che la stringa e' finita
}
void Attesa(char * str) {
cout << "\n\n\tPremere return per " << str;
cin.get();
}

Could you please tell me how can i solve? Thank you very much

Upvotes: 0

Views: 1288

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Modifying a string literal is undefined behavior.

char *st = "Stringa di tipo static\n";
           //this resides in read-only memory

Try declaring it as

char st[] = "Stringa di tipo static\n";
            //this is a string you own

Or, since this is C++, you should use std::string.

Upvotes: 2

Related Questions