Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 传递嵌套结构的地址';s成员_C - Fatal编程技术网

C 传递嵌套结构的地址';s成员

C 传递嵌套结构的地址';s成员,c,C,希望你们都做得很好。我试图将嵌套结构的成员的地址传递给函数,而当一切都可以通过gcc-std=c11-Wall-Wextra正常编译时,我遇到了一个分段错误。以下是编译删除-Wextra的最小代码,因为我没有将代码包含在验证中,只是在注释中进行解释: #include <stdio.h> #include <stdlib.h> struct string { char *str; int len; size_t siz; }; struct f

希望你们都做得很好。我试图将嵌套结构的成员的地址传递给函数,而当一切都可以通过
gcc-std=c11-Wall-Wextra
正常编译时,我遇到了一个分段错误。以下是编译删除
-Wextra
的最小代码,因为我没有将代码包含在
验证中,只是在注释中进行解释:

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

struct string
{
    char *str;
    int len;
    size_t siz;
};

struct file
{
    FILE *file;
    struct string path;
};

int validate(struct string s)
{
    /* returns 0 is the string is "valid", non-0 if not
    string is valid if:
    s.str is not NULL
    s.len is (int)strlen(s.str)
    s.siz is strlen(s.str) + 1
    this is here to make sure I don't accidentally pass a NULL
    s.str to printf for example and other undefined things */

    return 0; /* just returning 0 for this example */
}

int nullify(struct string* s)
{
    int freed = -1; /* count of free() calls */

    if (validate(*s) == 0)
    {
        free((*s).str);
        freed++;
    }

    (*s).str = NULL;
    (*s).len = 0;
    (*s).siz = 0;

    return freed;
}

int main()
{
    struct file file1;

    file1.file = NULL;
    nullify(&file1.path); /* i've tried everything I can think of here but
                             nothing seems to work */

    return 0;
}

你到底在释放什么?我没有看到
malloc
调用或
NULL
指针赋值
validate
返回0,因此对未初始化的
*s.str
调用
free
。请注意,
file1
未初始化,因此,
validate
的任何实现都无法工作。我想你需要一个无条件地将
文件
字符串
归零的函数。请看:我建议现在先忘掉
文件
altogther,并对纯
字符串
类型的变量进行详尽的测试。我真诚地祝你好运!在进行下一步之前,每次进行一步,并尽可能多地进行测试。顺便说一句,对于动态分配的字符串,
siz
是不需要的(除非你计划使用高级速度/空间优化技巧)。从给出的代码来看,我建议也忘记这一点。从谦虚开始,从那里开始。例如,如果您还没有,请检查
typedef
关键字并利用它(还有
(*s)。str
s->str
的详细等价物,等等)。
int validate(const struct string str)
{
    if (str.str == NULL)
    {
        return -1;
    }

    if (str.len != (int)strlen(str.str))
    {
        return -2;
    }

    if (str.siz != (strlen(str.str) + 1))
    {
        return -3;
    }

    return 0;
}