2013-04-09 1 views
0

C로 프로그램을 실행하고 있습니다. 프로그램을 실행할 때 세그먼트 오류 오류가 발생합니다. 내가 backtrace 할 때 gdb에서 알려준다.StString이 분할 오류를 생성 할 때 GetString()의 C 문자열

프로그램 수신 신호 SIGSEGV, Segmentation fault. ../sysdeps/i386/i686/multiarch/strlen-sse2-bsf.S:51 51 movdqu (%의 EDI)에서 __strlen_sse2_bsf(), % XMM1

나는 그것이 나 strlen과 관련이있다 생각합니다.

내가 나 strlen 사용하는 유일한 시간은 다음과 같습니다

string s = GetString(); 

    int stringlength = strlen(s); 

를 sizeof 오류가 중지를 위해 내가 나 strlen 변경합니다.

내 코드가 잘못되었습니다. 하여 GetString

/* 
* Reads a line of text from standard input and returns it as a 
* string (char *), sans trailing newline character. (Ergo, if 
* user inputs only "\n", returns "" not NULL.) Returns NULL 
* upon error or no input whatsoever (i.e., just EOF). Leading 
* and trailing whitespace is not ignored. Stores string on heap 
* (via malloc); memory must be freed by caller to avoid leak. 
*/ 

string GetString(void) { 
    // growable buffer for chars 
    string buffer = NULL; 

    // capacity of buffer 
    unsigned int capacity = 0; 

    // number of chars actually in buffer 
    unsigned int n = 0; 

    // character read or EOF 
    int c; 

    // iteratively get chars from standard input 
    while ((c = fgetc(stdin)) != '\n' && c != EOF) 
    { 
     // grow buffer if necessary 
     if (n + 1 > capacity) 
     { 
      // determine new capacity: start at 32 then double 
      if (capacity == 0) 
       capacity = 32; 
      else if (capacity <= (UINT_MAX/2)) 
       capacity *= 2; 
      else 
      { 
       free(buffer); 
       return NULL; 
      } 

      // extend buffer's capacity 
      string temp = realloc(buffer, capacity * sizeof(char)); 
      if (temp == NULL) 
      { 
       free(buffer); 
       return NULL; 
      } 
      buffer = temp; 
     } 

     // append current character to buffer 
     buffer[n++] = c; 
    } 

    // return NULL if user provided no input 
    if (n == 0 && c == EOF) 
     return NULL; 

    // minimize buffer 
    string minimal = malloc((n + 1) * sizeof(char)); 
    strncpy(minimal, buffer, n); 
    free(buffer); 

    // terminate string 
    minimal[n] = '\0'; 

    // return string 
    return minimal; 
} 
+1

'GetString'은 무엇을합니까? 나는 당신이 당신의 문자열을 null로 끝내지 않았다고 생각합니다 ... –

+0

''string''은 무엇입니까? ''std :: string'' 또는''char *''? – gongzhitaao

+0

@LeeTaylor 나는 그것이 C 문자열을 반환한다고 가정합니다. 문제는 문자열이 C++ 유형이고 strlen은 null로 끝나는 문자 배열을 필요로한다는 것입니다. – SevenBits

답변

4

getString() 함수의 설명

문서는 명확하게 오류 또는 EOF에 NULL을 반환 할 수 있다고.

확인하지 않고 strlen()에 반환 값을 전달하면 프로그램이 중단됩니다.

string s = GetString(); 
int stringlength = 0; 

if (s != 0) 
    stringlength = strlen(s); 

적어도이 작업은 중단되지 않습니다.

typedef char *string;의 원인과 그로 인한 이점에 대해 알 수 있습니다. 당신을 가르치는 사람들의 실수를 반복 할 필요가 없습니다.

// minimize buffer 
string minimal = malloc((n + 1) * sizeof(char)); 
strncpy(minimal, buffer, n); 
free(buffer); 

더 좋을 수 있고, 더 간단로 작성 :

나는 또한 코드 조각 관찰

string minimal = realloc(buffer, n + 1); 

올바른 크기로 할당을 축소 할 수 있습니다.

+0

strlen을 사용하여 문제를 해결하기 전에 null에 대한 점검 문자열을 보내 주셔서 감사합니다. 고맙습니다 – IberoMedia