[gcc] 같은 스코프 내에 선언된 배열 메모리 위치

PGD·2022년 1월 4일
0

같은 scope 내에 선언된 배열들은 서로 인접한 메모리에 할당된다.

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello, World!";
    char str2[5];

    strncpy(str2, str1, sizeof(str2) / sizeof(char));

    printf("%s\n", str2);
 
    return 0;
}
  • 실행 결과
HelloHello, World!

#include <stdio.h>
#include <string.h>

int main() {
    char* str1 = "Hello, World!";
    char str2[5];

    strncpy(str2, str1, sizeof(str2) / sizeof(char));

    printf("%s\n", str2);
 
    return 0;
}
  • 실행 결과
Hello

첫 번째 경우, str2에 할당된 메모리바로 뒤에 str1에 할당된 메모리가 바로 따라온다.

그렇기 때문에 str2에 null character가 저장되지 않아 실행 결과가 위와 같이 나온 것이다.

다음과 같은 실험 결과도 있다.


#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello, World!";
    char str2[] = "asdf";

    str2[strlen(str2)] = ' ';

    printf("%s\n", str2);
 
    return 0;
}
  • 실행 결과

    	asdf Hello, World!

이 실험은 상술한 가설을 뒷받침하는 근거가 된다.

위에서 두 번째 코드는 포인터 변수에 string literal을 할당한 것이다. 그러므로 char* str1char str2[5]는 서로 거리가 있는 위치의 메모리를 할당받는다.
이는 다음 실험을 통해 입증된다.


#include <stdio.h>
#include <string.h>

int main() {
    char* str1 = "Hello, World!";
    char str2[5];

    strncpy(str2, str1, sizeof(str2) / sizeof(char) - 1);
    str2[4] = ' ';

    printf("%s\n", str2);
 
    return 0;
}
  • 실행 결과
Hell
profile
student

0개의 댓글