Memory access violation (only with -O2).

Z

zombek

Hi.
When I comipile my program (source at the bottom) with : g++ -O2
-static it gives me 'memory access violation' warning and when I dont
use -O2 it doesn't. I need to use -O2 because my professor will use it
(automated tests). The error looks like I went out of array bounds but
I don't. How to solve it?

Szymon

--------------------------CODE-----------------------
#include <cstdio>

unsigned short nwd (unsigned short a, unsigned short b);

int main () {
unsigned short ile;
scanf ("%u", &ile);
unsigned short trojka [ile] [3];

for (int i = 0; i < ile; i++) {
scanf ("%u %u %u", &trojka [0], &trojka [1], &trojka
[2]);
}
for (int i = 0; i < ile; i++) {
printf ("trojka [%d] : %u %u %u\n", i, trojka [0], trojka
[1], trojka [2]);
}
unsigned short n;
for (int i = 0; i < ile; i++) {
n = nwd (trojka [0], trojka [1]);
printf ("nwd %u i %u : %u\n", trojka [0], trojka [1],
n);
}
return 0;
}

unsigned short nwd (unsigned short a, unsigned short b) {
unsigned short tmp;
while (b) {
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
 
D

Daniel T.

Hi.
When I comipile my program (source at the bottom) with : g++ -O2
-static it gives me 'memory access violation' warning and when I dont
use -O2 it doesn't. I need to use -O2 because my professor will use it
(automated tests). The error looks like I went out of array bounds but
I don't. How to solve it?

Solve it by using iostream instead of cstdio. "%u" is input for an
unsigned int, not an unsigned short.
Szymon

--------------------------CODE-----------------------
#include <cstdio>
#include said:
unsigned short nwd (unsigned short a, unsigned short b);

int main () {
unsigned short ile;
scanf ("%u", &ile); cin >> ile;
unsigned short trojka [ile] [3];

The above line it technically illegal. I suggest you use the Matrix
class from the FAQ instead.
http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.10
for (int i = 0; i < ile; i++) {
scanf ("%u %u %u", &trojka [0], &trojka [1], &trojka
[2]);

cin >> trojka( i, 0 ) >> trojka( i, 1 ) >> trojka( i, 2 );
}
for (int i = 0; i < ile; i++) {
printf ("trojka [%d] : %u %u %u\n", i, trojka [0], trojka
[1], trojka [2]);
}
unsigned short n;
for (int i = 0; i < ile; i++) {
n = nwd (trojka [0], trojka [1]);
printf ("nwd %u i %u : %u\n", trojka [0], trojka [1],
n);
}
return 0;
}

unsigned short nwd (unsigned short a, unsigned short b) {
unsigned short tmp;
while (b) {
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top