我正在C中運行一個程序。當我運行該程序時,出現分段錯誤錯誤。 IN gdb當我回溯它時告訴我當strlen產生分段錯誤時,來自GetString()的C字符串
程序接收到的信號SIGSEGV,分段錯誤。 __strlen_sse2_bsf()在../sysdeps/i386/i686/multiarch/strlen-sse2-bsf.S:51 51 MOVDQU(%EDI), %XMM1
我相信這與strlen的做。
我使用strlen唯一的一次是:
string s = GetString();
int stringlength = strlen(s);
當我改變的strlen用於sizeof停止錯誤。
我的代碼有什麼問題?的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;
}
GetString是做什麼的?我猜你沒有終止你的字符串... – 2013-04-09 01:55:24
什麼是''字符串'? ''std :: string''或''char *''? – gongzhitaao 2013-04-09 01:56:23
@LeeTaylor我假設它返回一個C字符串。那麼你的問題是string是一個C++類型,而strlen需要一個以null結尾的字符數組。 – SevenBits 2013-04-09 01:56:58