配列のオーバーフローについて
Posted: 2008年3月03日(月) 18:19
配列のオーバーフローについて語るトピをこちらに立てさせていただきました。
以下、他トピからうつした記事です。
以下、他トピからうつした記事です。
#include <stdio.h>
int main(void)
{
printf("%c\n", 3["abcde"]);
return 0;
} enum {
CH_CHANGE_NUM1_IDX0,
CH_CHANGE_NUM1_IDX1,
CH_CHANGE_NUM1_IDX2,
CH_CHANGE_NUM1,
};
int img_cshot1[CH_CHANGE_NUM1];
img_cshot1[CH_CHANGE_NUM1_IDX0] = 0; #include <iostream>
#include <vector>
int main(void)
{
std::vector<int> ary(4);
try {
ary.at(5) = 10;
} catch (std::out_of_range e) {
std::cout << "配列オーバー:" << e.what() << std::endl;
}
return 0;
} #include <iostream>
#include <vector>
template<class T>
class myvector : public std::vector<T> {
public :
myvector(int n) :
std::vector<T>(n)
{
}
~myvector() {
std::vector<T>::~vector();
}
T& at(int idx, const char* file, int line) {
if (idx < 0 || (unsigned int)idx >= size()) {
std::cout << file << ":" << line << "行目 " << "配列オーバー" << std::endl;
throw std::out_of_range("invalid myvector<T> subscript");
//return std::vector<T>::operator[/url](0);
}
return std::vector<T>::operator[/url](idx);
}
const T& at(int idx, const char* file, int line) const {
if (idx < 0 || (unsigned int)idx >= size()) {
std::cout << file << ":" << line << "行目 " << "配列オーバー" << std::endl;
throw std::out_of_range("invalid myvector<T> subscript");
//return std::vector<T>::operator[/url](0);
}
return std::vector<T>::operator[/url](idx);
}
T& operator [/url](int idx) {
if (idx < 0 || (unsigned int)idx >= size()) {
std::cout << "配列オーバー:" << idx << std::endl;
throw std::out_of_range("invalid myvector<T> subscript");
//return std::vector<T>::operator[/url](0);
}
return std::vector<T>::operator[/url](idx);
}
const T& operator [/url](int idx) const {
if (idx < 0 || (unsigned int)idx >= size()) {
std::cout << "配列オーバー:" << idx << std::endl;
throw std::out_of_range("invalid myvector<T> subscript");
//return std::vector<T>::operator[/url](0);
}
return std::vector<T>::operator[/url](idx);
}
};
#define at(n) at(n, __FILE__, __LINE__)
int main(void)
{
myvector<int> vec(1);
try {
vec[1] = 20;
} catch (...) {
}
try {
vec.at(1) = 20;
} catch (...) {
}
return 0;
} #include <iostream>
using namespace std;
class Hoge
{
public:
Hoge(){cout << "begin Hoge" << endl;}
~Hoge(){cout << "end Hoge" << endl;}
};
class HogeHoge :public Hoge
{
public:
HogeHoge(){cout << "begin HogeHoge" << endl;}
~HogeHoge(){cout << "end HogeHoge" << endl;}
};
int main()
{
Hoge *p = new HogeHoge;
delete p;
return 0;
}#ifdef _DEBUG
typedef myvector<int> IntArray;
#else
typedef std::vector<int> IntArray;
#endif struct BulletData {
int x, y, flg;
} bullet[100]; for (int i = 0; i < 100; ++i) {
BulletData* p = •
if (p->flg != 0) {
p->x = 0;
p->y = 0;
}
} template<class T>
class myvector : public std::vector<T> {
・・・
};
boost::shared_ptr<myvector<int> > vec;