디시인사이드 갤러리

갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

다음 언어는 무슨 언어일까요?

*루비*갤로그로 이동합니다. 2025.02.28 21:20:24
조회 38 추천 0 댓글 0

// This file contains an example that illustrates the use of strings in

// Checked C.  The example is adapted from "The C Programming Language,

// Second Edition", by Brian Kernighan and Dennis Ritchie, p. 69.

// It reads a series of lines and check whether a string occurs in a line.

// If it does, it prints the line.

//

// To compile the file using the Checked C version of clang, on Unix/Mac use

//  clang -o find-pattern find-pattern.c

// On Windows use:

//  clang -o find-pattern.exe find-pattern.c

//

// To run it, create a file with some lines of text in it that contain a

// pattern you wish to match.  Then run:

//    find-pattern {your pattern} < {your file name}

// where you use your pattern and file name in replace of {your pattern}

// and {your file name}.

//

// This file illustrates two important points about using strings in Checked C.

// - Sometimes you need to allocate a fixed size buffer that will be treated

//   as both a null-terminated string and a regular array.  The buffer should

//   be given a null-terminated array type, not a regular array type.

// - You will need to either allocate an extra character, or avoid writes to the

//   last character in the buffer.

// - Take care when using array subscripting on strings.  It is easy to accidentally

//   march beyond the end of the declared bounds.


#include <stdchecked.h>

#include <stdio_checked.h>


// In the original code, this is 1000.  Make this 50 so we can easily test

// exceeding the maximum number of characters allowed in a line.

#define MAXLINE 50


#pragma CHECKED_SCOPE ON


int getline(char line checked[] : count(max), int max);

int strindex(char source nt_checked[], char searchfor nt_checked[]);

void print_string(char str nt_checked[]);


int main(int argc, nt_array_ptr<char> argv checked[] : count(argc)) {

  if (argc < 2) {

    // Th original code used printf.  Calls to variable argument functions

    // aren't allowed in checked scopes, so use separate statements.

    print_string("Usage: ");

    print_string(argv[0]);

    print_string(" pattern\n");

    return -1;

  }

  nt_array_ptr<char> pattern = argv[1];

  // Line is treated is both a null-terminated array and a regular array. 

  // We don't allow array_ptrs to be converted to nt_array_ptrs, but we allow

  // the reverse. For this reason, we make this a null-terminated array.  Add

  // an extra byte so that we have a place for the null terminator and retain

  // the original size (the count of  accessible elements is one less than the

  // dimension of the array).

  char line nt_checked[MAXLINE + 1] = {};

  int found = 0;

  while (getline(line, MAXLINE) > 0)

    if (strindex(line, pattern) >= 0) {

      // Avoid using printf again;

      print_string(line);

      found++;

    }

  return 0;

}


// Get line into s, return length.

int getline(char s checked[] : count(lim), int lim) {

  int c, i;

  // The original code modifies lim, which we are using as the

  // bounds.  Introduce a new variable for counting the available

  // space.

  int available = lim;


  i = 0;

  while (--available > 0 && (c = getchar()) != EOF && c != '\n')

    s[i++] = c;

  if (c == '\n')

    s[i++] = c;

  // We could have made s a nt_checked array.  We'd have to check

  // here to make sure we aren't trying to write to the null terminator.

  s[i] = '\0';

  return i;

}


// Return index of t in s, -1 if none.

int strindex(char source nt_checked[] : count(0),

             char searchfor nt_checked[] : count(0)) {

  int i = 0, k = 0;


  nt_array_ptr<char> s : count(i) = source;

  nt_array_ptr<char> t : count(k) = searchfor;


  for (i = 0; s[i] != '\0'; i++) {

    // The original code was:

    //  for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)

    // The problem with this approach is that on the second iteration, j > i,

    // which will cause a runtime bounds failure for s[j].

    // We just introduce a temporary instead and remove s[j].

    nt_array_ptr<char> tmp_s = s + i;

    for (k = 0; t[k] != '\0' && *tmp_s == t[k]; tmp_s++, k++)

      ;

     if (k > 0 && t[k] == '\0')

       return i;

  }

  return -1;

}


void print_string(char str nt_checked[]) {

  // Fputs has a bounds-safe interface and can be used in checked scopes.

  fputs(str, stdout);

}




추천 비추천

0

고정닉 0

0

댓글 영역

전체 댓글 0
등록순정렬 기준선택
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 과음으로 응급실에 가장 많이 갔을 것 같은 스타는? 운영자 25/03/03 - -
2823992 [자유 대한민국] 비동의 강간죄 법안에 따른 대처방안 프갤러(121.172) 03.01 52 0
2823989 화교분탕들의 집요한 쏭 연애썰 날조 - 빌드업 ㅇㅇ(175.223) 03.01 39 0
2823987 자바 좆같은거 코틀린 쓴다고 안바뀐다. [3] 프갤러(110.8) 03.01 88 0
2823986 c언어 인강추천좀 프갤러(112.157) 03.01 36 0
2823985 와 C++에 async가 있을줄이야 ㅇㅅㅇ 강유현갤로그로 이동합니다. 03.01 68 0
2823984 [자유 대한민국] 부정선거와 언론이 거짓말인 이유- 프갤러(121.172) 03.01 52 1
2823983 북괴처 로동운 입건 수사 [4] ♥냥덩이♥갤로그로 이동합니다. 03.01 50 0
2823982 삼성 서비스 센터 쉬냐 버리고 오게 1만 5천원 넥도리아(112.170) 03.01 90 0
2823981 이거 15000원 주고 산 내가 바보이죠. 넥도리아(112.170) 03.01 52 0
2823980 매국친중 리죄명의 미래 ㅇㅅㅇ ♥냥덩이♥갤로그로 이동합니다. 03.01 29 0
2823979 나님 모종의 이유로 격투기 수련을 그만둔지 3개월차 [4] 딱님갤로그로 이동합니다. 03.01 56 0
2823978 취업 시장이 확실히 죽긴 죽었나봐 [2] 프갤러(59.16) 03.01 124 1
2823977 자바는 중국어와 같다 ㅇㅅㅇ [18] 강유현갤로그로 이동합니다. 03.01 104 1
2823976 짱깨 한국선거개입 발끈 발광 ♥냥덩이♥갤로그로 이동합니다. 03.01 34 0
2823975 짱깨가 대한민국 선거 운영한다 ♥냥덩이♥갤로그로 이동합니다. 03.01 48 0
2823974 powertoys 무겁네 [1] ㅇㅇ(119.56) 03.01 36 0
2823973 워드프레스 설치 겨우 성공했습니다 ㅠㅠ [1] *루비*갤로그로 이동합니다. 03.01 51 0
2823972 젤렌스키 이 극좌 전쟁광 병신 때문에 3차세계대전 터지겠노 ♥냥덩이♥갤로그로 이동합니다. 03.01 53 0
2823971 잘 익었쟈나❤ ♥냥덩이♥갤로그로 이동합니다. 03.01 30 0
2823970 10억 있으면 대한민국 10.9%안에 든다고 한다. 40대프린이(118.235) 03.01 37 0
2823969 지금 일어났다. [7] 40대프린이(118.235) 03.01 56 0
2823968 요번에 부천가서 납떼기 사왔으니, 다음에는 뭘살까요? 넥도리아(112.170) 03.01 25 0
2823967 LLM 너무 재밌다 진짜로 ㅋㅋ ㅇㅇ(106.101) 03.01 53 0
2823966 토스 미친놈들은 1원이자 주는걸 알림보내네 [15] 헬마스터갤로그로 이동합니다. 03.01 93 0
2823965 여자발까지 씻겨주던 연예인 결국 이혼한것으로 밝혀져. [1] 프갤러(211.219) 03.01 50 0
2823964 어떻게해야 세금을 아낄수있을까? 멍청한유라ㅋ갤로그로 이동합니다. 03.01 38 0
2823963 남친이 결혼하자한 라면 레시피 ㅇㅇㅇㅇ(121.126) 03.01 46 1
2823962 헬마이놈!!!!!!! [5] 멍청한유라ㅋ갤로그로 이동합니다. 03.01 52 1
2823961 일단 뭐라도 완성하는게 좋은 이유 [1] ㅇㅇ갤로그로 이동합니다. 03.01 180 0
2823960 동과 동 사이가 보통 1500보에서 3000보라고 보면됨. 넥도리아(112.170) 03.01 29 0
2823959 좀 웃기긴한듯 지망생을 오래하면 약간 현업과 동떨어짐 프갤러(211.210) 03.01 48 0
2823958 친중내란알바 폭로 ♥냥덩이♥갤로그로 이동합니다. 03.01 38 0
2823957 부정조작논란 선관위 사무처장 공산내란민주당과 커넥션 의혹 특검해야 [1] ♥냥덩이♥갤로그로 이동합니다. 03.01 43 0
2823956 안양시부터 광명시까지 3만보 아무나 따라하지 마삼. 넥도리아(112.170) 03.01 38 0
2823955 사실 도커네 뭐네 다 회사원들용 기술이지 슈퍼막코더(126.156) 03.01 36 0
2823954 핸드폰 고쳐줘 나우 넥도리아(112.170) 03.01 23 0
2823953 돈은 한없이 부족하구나 [11] 멍청한유라ㅋ갤로그로 이동합니다. 03.01 75 0
2823952 나라가 중국이나 미국에 넘어가면 안됩니까? [38] 멍청한유라ㅋ갤로그로 이동합니다. 03.01 95 0
2823951 오늘 한국이 유혈사태 없이 하루를 넘길수있을까요? [1] 헬마스터갤로그로 이동합니다. 03.01 51 0
2823950 윈도우10에서 테스트모드 생겼다가 갑자기 사라지는 머임? 프갤러(112.163) 03.01 43 0
2823946 화교분탕들의 집요한 쏭 연애썰 날조 헬스장 ㅇㅇ(175.223) 03.01 36 0
2823945 코딩이 재밌어서 학원 다닐라고 함 [3] 프갤러(172.225) 03.01 117 0
2823942 10400 cpu도 6코어12쓰레드입니다. 다만 as 여러번 받아서 벌크 넥도리아(112.170) 03.01 41 0
2823938 태연..ㅇㅅㅇ [1] 헤르 미온느갤로그로 이동합니다. 03.01 48 0
2823929 노브랜드 초콜릿 먹었고, 앞으로 먹을 것입니다. [2] 넥도리아(112.170) 03.01 48 0
2823923 노드 할려고 JS 배우는 사람 많음 ㅇㅅㅇ? 강유현갤로그로 이동합니다. 03.01 61 0
2823915 하루 한 번 헤르미온느 찬양 [3] 헤르 미온느갤로그로 이동합니다. 03.01 56 0
2823899 난 그동안 컴퓨터에 돈을 얼마나 썼을까.. 흠. *루비*갤로그로 이동합니다. 03.01 34 0
2823898 오늘은 nginx 설정만하고 약 먹고 자자 *루비*갤로그로 이동합니다. 03.01 30 0
2823893 요거 보고 nginx 설정 중 ㅋㅋ *루비*갤로그로 이동합니다. 03.01 40 0
뉴스 이혼 소송각…홍혜걸 “폐경 아내 매력 없어”→여에스더 “남편 외도” 폭로 디시트렌드 03.03
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2