gpt4 book ai didi

c - Valgrind 错误 : "Invalid read of size 1" due to strstr() with C

转载 作者:行者123 更新时间:2023-12-04 05:21:51 24 4
gpt4 key购买 nike

Valgrind 输出:

GET /cs3157/tng/index.html
==760== Invalid read of size 1
==760== at 0x4C2E7D4: strstr (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==760== by 0x400E67: HandleTCPClient (http-server.c:101)
==760== by 0x400D42: main (http-server.c:75)
==760== Address 0x0 is not stack'd, malloc'd or (recently) free'd

相关代码:
FILE *input = fdopen(clntSocket, "r");      //socket wrapped with FILE * 
if (input == NULL)
{
perror("fdopen failed");
fclose(input);
return;
}
char request_buffer[100];
char out_buf[BUF_SIZE];
int len, res;

while( fgets(request_buffer, sizeof(request_buffer),input) != NULL)
{
request_buffer[sizeof(request_buffer)-1] = '\0'; //null terminates buffer
char *request = request_buffer;
char *token_separators = "\t \r\n"; // tab, space, new line
char *method = strtok(request, token_separators);
char *requestURI = strtok(NULL, token_separators);
char *httpVersion = strtok(NULL, token_separators);

if( strstr(method,"GET") != NULL )
{
if( requestURI[strlen(requestURI)] == '/' )
requestURI = strcat(requestURI,"index.html");
printf("%s %s\n", method, requestURI);

}
memset(request_buffer,'\0',sizeof(request_buffer) );
}

fclose(input); //close the socket by closing the FILE * wrapper

我读到这个错误通常是由于未能为空终止字符串造成的。我认为 fgets() 之后的第一行可以防止出现问题。我猜我忽略了一些东西。我很感激任何帮助。

编辑:程序因段错误而崩溃。

最佳答案

听起来(来自 Valgrind 的报告)好像 methodNULL .您应该使用调试器逐步执行此代码,以验证标记化是否按预期工作。

此外,您应该将所有这些指针声明为 const char *因为它们不打算写入。这当然是一个小问题,但我尽量鼓励使用 const只要有可能。 :)

关于c - Valgrind 错误 : "Invalid read of size 1" due to strstr() with C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13601548/

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