디시인사이드 갤러리

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

갤러리 본문 영역

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

*루비*갤로그로 이동합니다. 2025.02.28 21:20:24
조회 54 추천 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/10 - -
2823831 자고 먹고 싸고 그러다 하루 다 갔네 ㅎㅎ *루비*갤로그로 이동합니다. 03.01 50 1
2823829 오늘의 출판 기획 실마리: 종교적 폭력 발명도둑잡기갤로그로 이동합니다. 03.01 38 0
2823825 SOLID 원칙에 관하여 [18] ㅆㅇㅆ(124.216) 03.01 895 9
2823824 싸우지 않는 대화법 발명도둑잡기갤로그로 이동합니다. 03.01 63 0
2823822 <승리호> 발명도둑잡기갤로그로 이동합니다. 03.01 48 0
2823819 몇 년 전에 초상화 그리기 배우는데 선생님이 연예인 사진 발명도둑잡기갤로그로 이동합니다. 03.01 43 0
2823815 자유오픈소스 개인, 법인 기여자 표시 발명도둑잡기갤로그로 이동합니다. 03.01 50 0
2823812 BSD와 비슷한 보이드 리눅스 발명도둑잡기갤로그로 이동합니다. 03.01 51 0
2823811 2019년 나랑 한국 아치/우분투쪽 사람들과 완전히 결별한 사건 [9] *루비*갤로그로 이동합니다. 03.01 88 1
2823809 20세기말~21세기초 신자유주의적 음악 특징 발명도둑잡기갤로그로 이동합니다. 03.01 82 0
2823806 윤석열 탄핵 만세! 발명도둑잡기갤로그로 이동합니다. 03.01 59 0
2823803 이메일 내용 동의 없이 공개 게시판에 게시할 경우 [9] *루비*갤로그로 이동합니다. 03.01 78 0
2823802 초중고 국악교육 폐지의 악영향 발명도둑잡기갤로그로 이동합니다. 03.01 49 0
2823801 존경하는 마이클무어의 <캐나다 침공 작전> 발명도둑잡기갤로그로 이동합니다. 03.01 39 0
2823799 대규모 리팩토링 중인데 조금 힘들다. 내가 생각하는 구상이 ㅆㅇㅆ(124.216) 03.01 54 0
2823790 프로그래밍 갤러리에 17 들어가는 사용자 두 명 있었다 발명도둑잡기갤로그로 이동합니다. 03.01 71 0
2823784 존경하는 봉감독님의 <미키 17> 봤다 발명도둑잡기갤로그로 이동합니다. 03.01 67 0
2823780 <씨네21> 틸다 트윈턴 팔레스타인 지지 비판 발명도둑잡기갤로그로 이동합니다. 03.01 44 0
2823779 권위주의적 성격 특징이 약한 모습 보이면 바로 버린다는 것 발명도둑잡기갤로그로 이동합니다. 03.01 62 0
2823778 김신영이 들려주는 '설문대할망 이야기' 발명도둑잡기갤로그로 이동합니다. 03.01 44 0
2823777 이번에 트럼프가 R&D 줄였다고하는데 우리나라 윤두창 떠오르노 ㅋㅋㅋㅋ [1] ㅆㅇㅆ(124.216) 03.01 81 0
2823776 자바는 시간이지날수록 돈지랄해도 도태되냐?? 뒷통수한방(1.213) 03.01 64 0
2823775 자바공화국 양키국 급속도로 망해가누 ㅋㅋ 뒷통수한방(1.213) 03.01 60 0
2823774 윤석열, '비동의 강간죄 도입' 막으려 대통령실 감찰까지? 발명도둑잡기갤로그로 이동합니다. 03.01 55 0
2823773 KBS, 부정선거 다룬 '추적 60분' 불방 발명도둑잡기갤로그로 이동합니다. 03.01 47 1
2823772 비동의 강간죄가 통과되려는 모양이네 ㅎㅎ *루비*갤로그로 이동합니다. 03.01 63 0
2823771 드라마 <마녀>가 인기래서 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 03.01 66 0
2823769 개별 메서드를 제네릭으로 만들었다 ㅆㅇㅆ(124.216) 03.01 60 0
2823768 ㅅㅂ명작이라니까 없는 이유도 찾아내게 되네 ㅋㅋㅋㅋㅋ ㅇㅇ(223.62) 03.01 59 0
2823767 드라마 <독수리 5형제를 부탁해>가 인기래서 생각나는 글 발명도둑잡기갤로그로 이동합니다. 03.01 91 0
2823766 세월호랑 무안참사랑 둘이 다를 수밖에 없는게 애초에 ㅆㅇㅆ(124.216) 03.01 149 1
2823765 드라마 <제로데이> 인기래서 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 03.01 48 0
2823764 국민들 여론은 다 언론이 만드는게 맞다 [6] hrin(220.120) 03.01 80 0
2823763 인공무현 최원종 옥바라지나 해볼까 [2] 프갤러(211.234) 03.01 62 0
2823762 ㅁㄱ아 ㅈㅎ아 ㅇㅇ아 잘들 지내야? ㅎㅎ [1] *루비*갤로그로 이동합니다. 02.28 60 0
2823761 젊었을 때 만났던 사람들은 얼굴이 기억이 안나니 원 *루비*갤로그로 이동합니다. 02.28 49 0
2823760 러·우 전쟁 3년…식량안보 교훈 되새길 때 발명도둑잡기갤로그로 이동합니다. 02.28 43 0
2823759 요새 만드는 워드프레스 설치 허접 스크립트 *루비*갤로그로 이동합니다. 02.28 59 0
2823758 서연님 사랑해요~~~ *루비*갤로그로 이동합니다. 02.28 50 0
2823757 러·우 전쟁 3년…식량안보 교훈 되새길 때 발명도둑잡기갤로그로 이동합니다. 02.28 45 0
2823756 복학생인데 고딩때 입던 스파이더 패딩 개씹오바냐?? ㅇㅇ(111.171) 02.28 47 0
2823755 하 시발구글 프갤러(49.165) 02.28 41 0
2823754 어느 1군 걸그룹 과대포장 의심되는 이유 ㅇㅇ(175.223) 02.28 64 0
2823753 C++ 좋다고 해봐야 소용 없다. 프갤러(59.16) 02.28 86 0
2823751 C++ 은 괴물이다. 프갤러(59.16) 02.28 67 0
2823750 본인은 방금 섹스하고 나옴 [4] hrin(220.120) 02.28 140 0
2823749 120mm 팬이 7개 있는데요.. *루비*갤로그로 이동합니다. 02.28 58 0
2823748 10년안에 ai운영체제 나올거임 ㅇㅇ(211.246) 02.28 46 0
2823747 절망 밖에 없어 자러 간다. 넥도리아(112.170) 02.28 72 0
2823746 K엔터의 자회사 S엔터의 상장에 물린 사람들 ㅇㅇ(110.70) 02.28 55 0
뉴스 배우 이상인 첫째 자폐 의심…부인 “주부 사표 내고 도망가고 싶다” 오열 디시트렌드 03.09
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2