[질문] 이게 왜 세그폴트가 날까요?

gostop의 이미지

int port, ch;

while((ch=getopt(argc, argv, "p"))!=EOF) {
        switch(ch) {
                case 'p':
                        port=atoi(optarg);
                        break;
                default:
                        exit(0);
                }
}
printf("port: %d\n", port);

./port -p 4941
Segmentation fault (core dumped)
차리서의 이미지

getopt(3)의 세번째 인수는 "p"가 아니라 "p:"여야할 것 같습니다.

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
        int     port, ch;

        while ((ch = getopt(argc, argv, "p:")) != EOF) {
                switch (ch) {
                case 'p':
                        port = atoi(optarg);
                        break;
                default:
                        exit(EXIT_SUCCESS);
                }
        }
        printf("port: %d\n", port);

        return (EXIT_SUCCESS);
}

잘 실행되는군요:
> cc -o port port.c
> ./port -p 4941
port: 4941
>

--
자본주의, 자유민주주의 사회에서는 결국 자유마저 돈으로 사야하나보다.
사줄테니 제발 팔기나 해다오. 아직 내가 "사겠다"고 말하는 동안에 말이다!