메모리 (1)

khxxjxx·2021년 4월 20일
0

강좌 : 부스트캠프 모두를 위한 컴퓨터과학(cs50 2019)

4. 메모리

✍문자열 (1)

문자열 비교

get_string : 호출될때마다 포인터를 반환

  • 메모리 공간의 첫 바이트 주소를 반환하게 되어있기 때문에 문자열을 비교할땐 따로 함수를 이용해줘야 한다
#include<cs50.h>
#include<stdio.h>
#include<string.h>

int main(void)
{
    string s = get_string("s: ");
    string t = get_string("t: ");

    if(strcmp(s,t) == 0)
    {
        printf("same\n");
    }
    else
    {
        printf("different\n");
    }
}

문자열 복사

사용자에게 입력값을 받아 첫글자를 대문자로 출력하기

#include<cs50.h>
#include<ctype.h>  //toupper을 사용하기 위한 헤더파일
#include<stdio.h>

int main(void)
{
    string s = get_string("s: ");
    // s라는 변수에 문자열이 아닌 그 문자열이 있는 메모리의 주소가 저장
    string t = s;
    // 따라서 t도 동일한 주소를 가르킨다
    
    t[0] = toupper(t[0]);  // 동일한 주소이므로 t를 통한 수정은 s에도 반영
    
    printf("s: %s\n",s);
    printf("t: %s\n",t);
    // s와 t 동일하게 출력
}

malloc : 정해진 크기만틈 메모리를 할당하는 함수

#include<cs50.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h>  //strlen을 사용하기 위한 헤더파일
#include<stdlib.h>  // malloc를 사용하기 위한 헤더파일

int main(void)
{
    string s = get_string("s: ");
    string t = malloc(strlen(s)+1);  // 메모리 할당함수를 사용해 t 정의 
    // 문자열길이 + 널종단문자
    for(int i = 0, n = strlen(s); i < n + 1; i++)
    {  
    	t[i] = s[i];  // for 함수를 이용해 널종단문자까지 카피
    }
    
    t[0] = toupper(t[0]);
    
    printf("s: %s\n",s);
    printf("t: %s\n",t);
}

strcpy : 문자열 카피 함수

#include<cs50.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
    string s = get_string("s: ");
    string t = malloc(strlen(s)+1);
    
    strcpy(t, s);  // for 함수대신 간단히 문자열 카피
    
    t[0] = toupper(t[0]);
    
    printf("s: %s\n",s);
    printf("t: %s\n",t);
}

✍메모리 할당과 해제

  • malloc 함수를 이용하여 메모리를 할당한 후에는 free라는 함수를 이용하여 메모리를 해제해야한다
  • 그렇지 않아 메모리 용량의 낭비가 발생하는 것을 메모리 누수 라고 말한다
  • $ help50 valgrind ./파일명 명령어를 사용하면 파일에 대한 valgrind 검사 내용을 확인할 수 있다

✍️메모리 교환

swap : 정수를 입력받아 그 값을 바꾸는 일을 수행

메모리저장값
machine code컴파일된 바이너리
globals프로그램 안에서 저장된 전역변수
heap


쌓이면서 저장


stack
malloc으로 할당된 메모리의 데이터




프로그램 내의 함수와 관련된 것들
// 잘못된 코드
#include <stdio.h>


void swap(int a, int b);

int main(void)
{
    int x = 1;
    int y = 2;

    printf("x is %i, y is %i\n", x,y);
    swap(x,y);
    printf("x is %i, y is %i\n", x,y);  // 위와 같은 결과가 출력된다
}

void swap(int a, int b)
{
    int tmp = a;
    a = b;
    b = tmp;
}
  • a, b, x, y, tmp 모두 스택영역에 저장되지만 a와 x, b와 y는 그 안에서도 서로 다른 위치에 저장된 변수이다
  • 따라서 a와 b를 각각 x와 y를 가르키는 포인터로 지정함으로 써 이문제를 해결할 수 있다
// 올바른 코드
#include <stdio.h>


void swap(int *a, int *b);

int main(void)
{
    int x = 1;
    int y = 2;

    printf("x is %i, y is %i\n", x,y);
    swap(&x, &y);  // x와 y의 주소를 불러온다
    printf("x is %i, y is %i\n", x,y);  // x와 y값이 바뀐 결과가 출력된다
}

void swap(int *a, int *b)  // 불러온 주소로 a와 b가 간다
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}
profile
코린이

0개의 댓글