본문 바로가기

소프트웨어/C/C++

c] data영역과 text영역







#include<stdio.h>

#include<stdlib.h>

#include<string.h>


char a[]="rose"; // ok


int main(void) {

char b[]="rose"; //ok

char *p ="grace"; //ok, p에 상수 grace의 주소가 들어간다.

 // 포인터는 데이터 영역(data segment)에 저장되므로 수정이 가능하나(주소값을 바꿔는것과 같이)

 // grace는 문자열 상수이므로 text영역(text segment)에 저장된다. 그래서 수정 권한이 없다.

char buff[]="grace"; //buff Array에 grace 할당

char* p2= buff; //p2가 buff를 가리키도록 주소를 넣는다.

p2[0] = 't';


a[0]='n'; //ok

b[0]='n'; //ok

//p[0]='t'; //not ok, p는 grace라는 상수 char*를 가리키는데 값 변경을 시도해서 Err

//p=b; //ok, p값은 pointer이기때문에 b의 주소를 주면 b를 가리키게된다.(==p가 nose를 갖는 Array인 b를 가리킨다)

//p="changeNewAddressInTextSegment"; //ok, p가 가리키는 text영역에서 수정이 아닌 새로운 char*를 가리키게 바꾸는건 가능하다


printf("a=%s \n", a);

printf("b=%s \n", b);

printf("p=%s \n", p);


{

char buff[]="grace"; //buff Array에 grace 할당

char* p2= buff; //p2가 buff를 가리키도록 주소를 넣는다.

printf("변경 전 p2=%s \n", p2);

p2[0] = 't'; //p2가 가리키는 변수 buff Array의 0번째 값을 바꾼다.


printf("변경 후 p2=%s \n", p2);

printf("p2를 변경 후 buff값=%s \n", buff);

}


return 0;

}