gpt4 book ai didi

c - 错误 : KERN_INVALID_ADDRESS at address: 0x0000000000000000 0x00007fff99b359c4 in strstr ()

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:12 30 4
gpt4 key购买 nike

我在 Mac OS X 上编写了一个小程序,但在以下函数中出现以下错误:

Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000 0x00007fff99b359c4 in strstr ()

/*
* attrvalue(): parse an attribute value pair.
*
* takes a string of the form "ATTRIBUTE = VALUE" and returns the atrribute name
* and value as seperate strings
*
*/
int
attrvalue(char *entry, char **attr, char **value)
{
char *copy;
char *p;

if (!entry || *entry == '\0')
return 1;

copy = strdup(entry);

*attr = strtok(copy, "=");
*value = strtok(NULL, "\n");

/* strip training whitespace from attr and value */
p = strstr(*attr, " ");
if(p)
*p = '\0';
p = strstr(*value, " ");
if(p)
*p = '\0';
return (0);
}

知道这个函数有什么问题吗?

谢谢。

最佳答案

修改后的答案:如果你假设在 attr 或 value 的开头没有空格(即行的开头和 attr 字符串之间,或者等号和 value 字符串之间没有空格),那么你的程序可以只需稍作调整即可工作:将 strstr() 的第二个参数中的多个空格更改为单个空格。带有用于演示的 main() 的修订代码如下。如果您希望去除非尾随空格,那么,当您扩展问题或从下面我的原始答案中的链接借用时,它可能会返回调试器。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*
* attrvalue(): parse an attribute value pair.
*
* takes a string of the form "ATTRIBUTE = VALUE" and returns the atrribute name
* and value as seperate strings
*
*/
int
attrvalue(char *entry, char **attr, char **value)
{
char *copy;
char *p;

if (!entry || *entry == '\0')
return 1;

copy = strdup(entry);

*attr = strtok(copy, "=");
*value = strtok(NULL, "\n");

/* strip trailing whitespace from attr and value */
p = strstr(*attr, " ");
if(p)
*p = '\0';
p = strstr(*value, " ");
if(p)
*p = '\0';
return (0);
}

int main()
{
char *input = "asdf =blah "; // this works
//char *input = " asdf = blah"; // this would not
char *attr;
char *value;

attrvalue(input, &attr, &value);

printf("attr =\"%s\"", attr);
printf("value=\"%s\"", value);

return 0;
}

原回答:我会使用一种不同的方法来去除空格,因为它甚至不太清楚 strstr() 在这种情况下如何工作。这是 strstr() documentation , 这是一个 SO topic discussing the removal of whitespace in C .

结合其他想法:

  • if(p) 应该是 if(p != NULL),作为 nit。
  • 如果 strstr() 的第二个参数比第一个长怎么办?

关于c - 错误 : KERN_INVALID_ADDRESS at address: 0x0000000000000000 0x00007fff99b359c4 in strstr (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14802359/

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