Linux API/linux2023. 11. 13. 17:35

무지성으로 mmap이니 반대 짝이 먼지 찾아서 munmap 하고 쓰고 있었는데

mmap과 malloc의 차이 그리고 malloc이 어떻게 구현되어있는지 문득 궁금해졌다.

 

munmap 서브루틴은 맵핑된 파일이나 공유 메모리 영역 또는 익명 메모리 영역을 맵핑 해제합니다. munmap 서브루틴은 호출에서 작성된 영역을 mmap 서브루틴으로만 맵핑 해제합니다.

주소가 munmap 서브루틴에 의해 맵핑되지 않은 리젼에 있고 해당 리젼이 이후에 다시 맵핑되지 않는 경우, 해당 주소에 대한 모든 참조로 인해 프로세스에 SIGSEGV 신호가 전달됩니다.

[링크 : https://www.ibm.com/docs/ko/aix/7.3?topic=m-munmap-subroutine]

 

mmap()에서는 할당 메모리의 크기가 최소 4KB(mmap()은 페이지 크기의 배수로 할당).
malloc()은 큰 메모리 블록 요청이 들어오면 내부적으로 mmap()을 써서 메모리를 할당한다. 
mmap()이 malloc()을 포함하는 개념이라기보다 mmap()은 시스템에서 제공하는 저수준 시스템 콜이며 특별한 조건일 때 메모리를 할당하는 효과를 볼 수 있다. malloc()은 메모리를 할당하는 C library 함수이며 내부적으로 mmap(), brk() 등 시스템 콜을 써서 구현.

[링크 : https://woonys.tistory.com/entry/정글사관학교-51일차-TIL-mmap과-malloc-차이-정리]

[링크 : https://mintnlatte.tistory.com/357]

 

직접 mmap()을 쓸 경우, valgrind/efence/duma 등 메모리 디버깅 툴의 도움을 받을 수도 없습니다.

[링크 : https://kldp.org/node/101737]

 

malloc.c 에서 함수를 찾는데 mmap을 먼저 찾고 역으로 올라가면서 찾아보는 중

static void *
sysmalloc (INTERNAL_SIZE_T nb, mstate av)
{
      if ((unsigned long) (size) > (unsigned long) (nb))
        {
          mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
        }
}


static void *
_int_malloc (mstate av, size_t bytes)
{
  if (__glibc_unlikely (av == NULL))
    {
      void *p = sysmalloc (nb, av);
      if (p != NULL)
alloc_perturb (p, bytes);
      return p;
    }
}


void *
__libc_malloc (size_t bytes)
{
  if (SINGLE_THREAD_P)
    {
      victim = _int_malloc (&main_arena, bytes);
      assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
      &main_arena == arena_for_chunk (mem2chunk (victim)));
      return victim;
    }

  arena_get (ar_ptr, bytes);

  victim = _int_malloc (ar_ptr, bytes);
}

[링크 : https://elixir.bootlin.com/glibc/glibc-2.26/source/malloc/malloc.c]

 

위의 함수들에 대한 자세한 설명은 아래 참조

[링크 : https://m.blog.naver.com/yjw_sz/221549666704]

'Linux API > linux' 카테고리의 다른 글

리눅스 커널 6.6.6 릴리즈  (0) 2023.12.13
mmap() 과 munmap() 예제  (0) 2023.11.17
/proc/uptime  (0) 2023.10.24
/proc/pid/statm  (0) 2023.10.23
malloc() 으로 할당된 메모리 리스트?  (0) 2023.10.19
Posted by 구차니
개소리 왈왈/컴퓨터2023. 11. 12. 23:35

hdd 케이지는 강성 부족으로 케이스가 덜덜덜..

역시 hdd는 케이스가 무거워야 겠구먼..

어찌어찌 서버도 1tb 8개는 될 것 같으니

raid나 구성하고 박살내봐야겠다

Posted by 구차니

딸래미 생일이라 가족들과 외식하고

집에왔다 오랫만에 스타필드 가서는 왕창 쓰고 옴

그 와중에 중앙 통로... 티니핑.. 으아아아아 위험해!

'개소리 왈왈 > 육아관련 주저리' 카테고리의 다른 글

체외충격파는 아직 무서워  (0) 2023.11.15
내일은 수능날  (0) 2023.11.14
어깨 떄문에 뒷목이 아프다 ㅠㅠ  (0) 2023.10.28
통깁스  (0) 2023.10.26
으아아아앙  (0) 2023.10.23
Posted by 구차니
Programming/golang2023. 11. 10. 14:30

아놔.. 너무 심하게 강형 언어인거 아닌가 싶을 정도로

별별것 다 트집을 잡아서 명시적으로 형변환을 하게 만든다

time.Sleep(2 * time.Second) // 정상 작동

var update_sec int = 2
time.Sleep(update_sec * time.Second) // 에러

time.Sleep(time.Duration(update_sec) * time.Second) // 정상 작동

[링크 : https://jusths.tistory.com/71]

 

아니면 내가 너무 golang을 golang 답게 안쓰는건가?

'Programming > golang' 카테고리의 다른 글

golang용 swagger  (0) 2024.01.17
golang echo static web / logo.* 안돼?  (0) 2023.12.08
golang 타입 캐스팅 제약(?)  (0) 2023.11.09
golang 배열과 슬라이스  (0) 2023.11.08
golang ini 지원  (0) 2023.11.07
Posted by 구차니
Programming/golang2023. 11. 9. 10:58

눈에도 안들어 온다 으아아

[링크 : https://stackoverflow.com/questions/28040896/why-can-not-convert-sizebyte-to-string-in-go]

 

슬라이스를 배열로 하려면 copy 해야 하는 듯

package main
import "fmt"

//create main function to execute the program
func main() {
   var slice []int // initialize slice
   slice = append(slice, 10) //fill the slice using append function
   slice = append(slice, 20)
   slice = append(slice, 30)
   
   // Convert the slice to an array
   array := [3]int{} //initialized an empty array
   copy(array[:], slice) //copy the elements of slice in newly created array
   fmt.Println("The slice is converted into array and printed as:")
   fmt.Println(array) // prints the output: [10 20 30]
}

[링크 : https://www.tutorialspoint.com/golang-program-to-convert-slice-into-array]

'Programming > golang' 카테고리의 다른 글

golang echo static web / logo.* 안돼?  (0) 2023.12.08
golang 타입 땜시 짜증  (0) 2023.11.10
golang 배열과 슬라이스  (0) 2023.11.08
golang ini 지원  (0) 2023.11.07
golang 함수인자에 배열 포인터  (0) 2023.11.07
Posted by 구차니
개소리 왈왈/컴퓨터2023. 11. 8. 22:47

키보드는 ctrl 왼쪽이 잘 안눌려서

묘하게 복사 붙여 넣기가 한번에 안되고

 

마우스는 미묘~~하게 좌클릭이 안된다

다이소 가서 사야하나..

'개소리 왈왈 > 컴퓨터' 카테고리의 다른 글

오늘의 당근은 실패  (0) 2023.11.23
mitx 환상 와장창  (0) 2023.11.12
synology 213j 7.x 업데이트  (0) 2023.11.06
몇일 늦은 사진 없는 개봉기 - 조이트론 웹캠  (0) 2023.10.31
mitx 한대 줍줍  (0) 2023.10.30
Posted by 구차니
Programming/golang2023. 11. 8. 22:34

다시 a tour of go 봐야 할 듯..

 

Arrays
The type [n]T is an array of n values of type T.

The expression

var a [10]int
declares a variable a as an array of ten integers.

An array's length is part of its type, so arrays cannot be resized. This seems limiting, but don't worry; Go provides a convenient way of working with arrays.

[링크 : https://go.dev/tour/moretypes/6]

 

 

Slices
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

The type []T is a slice with elements of type T.

A slice is formed by specifying two indices, a low and high bound, separated by a colon:

a[low : high]
This selects a half-open range which includes the first element, but excludes the last one.

The following expression creates a slice which includes elements 1 through 3 of a:

a[1:4]

[링크 : https://go.dev/tour/moretypes/7]

 

 

크기가 정해지면 array, 정해지지않으면 slice인가?

Since you didn't specify the length, it is a slice.
An array type definition specifies a length and an element type: see "Go Slices: usage and internals"

[링크 : https://stackoverflow.com/questions/29361377/creating-a-go-slice-without-make]

 

 

갑자기 length와 capacity?!

A slice literal is declared just like an array literal, except you leave out the element count:

letters := []string{"a", "b", "c", "d"}

slice can be created with the built-in function called make, which has the signature,

func make([]T, len, cap) []T

where T stands for the element type of the slice to be created. The make function takes a type, a length, and an optional capacity. When called, make allocates an array and returns a slice that refers to that array.

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}

When the capacity argument is omitted, it defaults to the specified length. Here’s a more succinct version of the same code:

s := make([]byte, 5)

The length and capacity of a slice can be inspected using the built-in len and cap functions.

len(s) == 5
cap(s) == 5

[링크 : https://go.dev/blog/slices-intro]

 

 

실제 사용시에 capacity까지 알 필요는 없을려나?

capacity: 실제 메모리에 할당된 공간입니다. 만약 슬라이스에 요소를 추가하여 capacity가 가득차면 자동으로 늘어납니다.

[링크 : https://www.pymoon.com/entry/Go-튜토리얼-배열-슬라이스]

[링크 : https://phsun102.tistory.com/82]

[링크 : https://go.dev/tour/moretypes/11]

 

 

2차원 배열은 [][]type 으로 생성하면되는데

make를 통해서도 2차원 배열이 생성가능한진 모르겠다

package main

import "fmt"

func main() {
    // Step 1: create empty collection.
    values := [][]int{}

    // Step 2: these are the first two rows.
    // ... Append each row to the two-dimensional slice.
    row1 := []int{1, 2, 3}
    row2 := []int{4, 5, 6}
    values = append(values, row1)
    values = append(values, row2)

    // Step 3: display first row, and second row.
    fmt.Println("Row 1")
    fmt.Println(values[0])
    fmt.Println("Row 2")
    fmt.Println(values[1])

    // Step 4: access an element.
    fmt.Println("First element")
    fmt.Println(values[0][0])
}
Row 1
[1 2 3]
Row 2
[4 5 6]
First element
1

[링크 : https://www.dotnetperls.com/2d-go]

 

 

 

make와 := []type 두개가 동등하다면 가능할지도?

package main

import (
"fmt"
"strings"
)

func main() {
// Create a tic-tac-toe board.
board := [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}

// The players take turns.
board[0][0] = "X"
board[0][2] = "X"
board[1][0] = "O"
board[1][2] = "X"
board[2][2] = "O"


for i := 0; i < len(board); i++ {
fmt.Printf("%s\n", strings.Join(board[i], " "))
}
}
X _ X
O _ X
_ _ O

[링크 : https://go.dev/tour/moretypes/14]

'Programming > golang' 카테고리의 다른 글

golang 타입 땜시 짜증  (0) 2023.11.10
golang 타입 캐스팅 제약(?)  (0) 2023.11.09
golang ini 지원  (0) 2023.11.07
golang 함수인자에 배열 포인터  (0) 2023.11.07
c to golang online converter  (0) 2023.11.07
Posted by 구차니
Programming/golang2023. 11. 7. 15:29

텍스트로 보이는 환경설정 파일로는 ini만한게 없지..

 

[링크 : https://pkg.go.dev/gopkg.in/ini.v1]

[링크 : https://github.com/go-ini/ini/]

[링크 : https://minwook-shin.github.io/read-and-write-ini-files-ini/]

'Programming > golang' 카테고리의 다른 글

golang 타입 캐스팅 제약(?)  (0) 2023.11.09
golang 배열과 슬라이스  (0) 2023.11.08
golang 함수인자에 배열 포인터  (0) 2023.11.07
c to golang online converter  (0) 2023.11.07
golang slice  (0) 2023.11.07
Posted by 구차니
Programming/golang2023. 11. 7. 14:38

c 들어내고 go로만 짜려니 어렵네..

함수 인자로 포인터를 넘겨줄 때에도 변수의 크기 정보가 넘어가야 한다.

그래서 정확한 포인터의 길이가 함수 인자에 지정되어야 한다.

그럼.. 굳이 포인터 쓸 필요가 없어지는거 아닌가?

 

// Golang program to pass a pointer to an 
// array as an argument to the function 
package main 
  
import "fmt"
  
// taking a function 
func updatearray(funarr *[5]int) { 
  
    // updating the array value 
    // at specified index 
    (*funarr)[4] = 750 
      
    // you can also write  
    // the above line of code 
    // funarr[4] = 750 

  
// Main Function 
func main() { 
  
    // Taking an pointer to an array 
    arr := [5]int{78, 89, 45, 56, 14} 
  
    // passing pointer to an array 
    // to function updatearray 
    updatearray(&arr
  
    // array after updating 
    fmt.Println(arr) 

[링크 : https://www.geeksforgeeks.org/golang-pointer-to-an-array-as-function-argument/]

'Programming > golang' 카테고리의 다른 글

golang 배열과 슬라이스  (0) 2023.11.08
golang ini 지원  (0) 2023.11.07
c to golang online converter  (0) 2023.11.07
golang slice  (0) 2023.11.07
golang echo bind  (0) 2023.11.06
Posted by 구차니
Programming/golang2023. 11. 7. 12:11

꿀~ 개꿀~ dog honey~

 

[링크 : https://kalkicode.com/c-to-golang-converter-online]

'Programming > golang' 카테고리의 다른 글

golang ini 지원  (0) 2023.11.07
golang 함수인자에 배열 포인터  (0) 2023.11.07
golang slice  (0) 2023.11.07
golang echo bind  (0) 2023.11.06
golang echo 구조체 배열은 미지원?  (0) 2023.11.06
Posted by 구차니