간단한 C 코드, 이해 할 수 없는 세그먼테이션 폴트

jose의 이미지

#include <stdio.h>
 
#define LIMIT 10
 
int main(void)
{
        int i, j, t, index[LIMIT];
//        int arr[LIMIT] = {166, 252, 163, 160, 193, 265, 288, 166, 227, 245};
        int arr[LIMIT] = {  4,   5,  21,   5,   6,  44,  22,   5,  76,   9};
 
                for(i= 0; i< LIMIT; i++)
                        index[i] = i;
 
                for(i= 1; i< LIMIT; i++){
                        t= index[i];
                        j= i;
                                while(arr[index[j- 1]]> arr[t] && j> 0){
                                        index[j]= index[j- 1];
                                        j--;
                                }
                        index[j]= t;
                }
 
                for(i= 0; i< LIMIT; i++)
                        printf("%4d", arr[index[i]]);
 
        putchar('\n');
 
        return 0;
}

index 배열을 이용한 간단한 간접정렬입니다.
현 소스 그대로 컴파일/실행 하면 의도한 대로 동작합니다.
그런데, 주석처리 된 8번째 라인 데이터를 사용하기 위해 아래 9번째 라인에 주석처리를 하고 8번째 라인 주석을 제거한 뒤, 컴파일/실행하면 세그먼테이션 폴트가 일어납니다.

gcc version 3.4.2 와 Dev C++ 4.9.9.2 에서 테스트 해봤습니다.

------
먼저, 아래 답변 주신 분들 모두 감사드립니다.

그런데 질문을 다시 한번 올려야 하나 싶습니다.
논리적 결함이면 몰라도 [-1]과 같은 접근이 직접적인 오류를 일으키진 않습니다. 실제로 가변인수를 다룰 때 이와 같은 연산을 하기도 하고요. 그러니까 위의 소스에서 [-1]로 접근을 했더라도 후위에 && j> 0 조건이 [-1]로의 값 대입을 방지합니다. 결국 1. j> 0의 위치변화는 아무런 위해를 끼칠 수가 없어야 하는데?, 그리고 2. j> 0의 위치변화가 적법한 조치였다면 8, 9라인의 입력값 수정만으로 동작이 변화하는 까닭은 또 무엇일까요?

sangheon의 이미지

결과의 정확성은 살펴보지 않았습니다. :-)

#include <stdio.h>
 
#define LIMIT 10
 
int main(void)
{
        int i, j, t, index[LIMIT];
        int arr[LIMIT] = {166, 252, 163, 160, 193, 265, 288, 166, 227, 245};
//        int arr[LIMIT] = {  4,  5,  21,  5,  6,  44,  22,  5,  76,  9};
 
                for(i= 0; i< LIMIT; i++)
                        index[i] = i;
 
                for(i= 1; i< LIMIT; i++){
                        t= index[i];
                        j= i;
                                while(j> 0 && arr[index[j- 1]]> arr[t]){
                                        index[j]= index[j- 1];
                                        j--;
                                }
                        index[j]= t;
                }
 
                for(i= 0; i< LIMIT; i++)
                        printf("%4d", arr[index[i]]);
 
        putchar('\n');
 
        return 0;
}

B/o/o/k/w/o/r/m/

--

Minimalist Programmer

ㅡ,.ㅡ;;의 이미지

while(j> 0 && arr[index[j- 1]]> arr[t]){

윗분말씀처럼 j 값의 채크가 앞에 와야죠.. 그렇지 않으면 arr[-1] 의 값을 비교하게 되니 에러가납니다..


----------------------------------------------------------------------------

joobeom의 이미지

for (; j > 0; j--) {
if (arr[index[j- 1]] > arr[t]) {
.....
}
}

이렇게 하시는 것이 좋을 것 같습니다.

ㅡ,.ㅡ;;의 이미지

이것은 좀틀립니다.

약간손해혹은 이코드는 발생하지않을지몰라도 오류가능성도 있다고 봐야죠..

else break; 를 더 보강해야 비슷하겠네요..


----------------------------------------------------------------------------

jiee의 이미지

토나오게...

cppig1995의 이미지

arr[-1]을 읽는 것만으로도 오류를 일으킬 수 있습니다;;;

Real programmers /* don't */ comment their code.
If it was hard to write, it should be /* hard to */ read.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.