gpt4 book ai didi

当 strlen 产生段错误时来自 GetString() 的 C 字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:06 31 4
gpt4 key购买 nike

<分区>

我正在用 C 语言运行一个程序。当我运行该程序时,出现段错误。在 gdb 中,当我回溯时它告诉我

Program received signal SIGSEGV, Segmentation fault. __strlen_sse2_bsf () at ../sysdeps/i386/i686/multiarch/strlen-sse2-bsf.S:51 51 movdqu (%edi), %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;
}

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com