2

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

程序收到信号 EXC_BAD_ACCESS,无法访问内存。原因:KERN_INVALID_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);
}

知道这个功能有什么问题吗?

谢谢。

4

1 回答 1

0

Revised answer: If you assume that there is no whitespace at the beginning of either attr or value (i.e., there is no space between the start of the line and the attr string, or the equal sign and the value string), then your program can be made to work with only a slight adjustment: change the multiple spaces in the second arguments to strstr() to single spaces. The revised code with a main() to demonstrate follows. If you wish to strip non-trailing whitespace, then, well, it's likely back to the debugger as you expand the problem or borrowing from the link in my original answer below.

#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;
}

Original answer: I'd use a different method of stripping out whitespace, as it's not even quite clear how strstr() would work as used in this situation. Here's the strstr() documentation, and here's a SO topic discussing the removal of whitespace in C.

Couple other thoughts:

  • if(p) should be if(p != NULL), as a nit.
  • What if second argument to strstr() is longer than the first?
于 2013-02-10T20:53:57.627 回答