繁体   English   中英

C分段错误:函数strcmp之间的内存已更改

[英]C Segmentation fault: memory altered between functions strcmp

如果有人可以告诉我为什么populate()返回dir后无法访问dir.paths [dir.npaths]处的内存,以及如何修复它。 那将不胜感激。

这是问题的简化,它与所有核心要素紧密结合。 我只需要知道如何进行比较而不会遇到分段错误。

比较实际上是在if语句中使用的。 例如。 如果(strcmp(dir ...,“ file”)== 0)

在完整程序中,搜索将填充并成为递归调用。 这意味着我不能只将strcmp移到填充函数中。 他们需要分开。

//测试从函数填充开始

// seek()函数中的strcmp导致分段错误

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

typedef struct
{
    string name;
     string type;
}
path;

typedef struct
{
    int npaths;
    path* paths;
}
directory;

//原型

int seek(directory dir);


int main(void)
{
     directory dir;
     seek(dir);
}

//实际测试在此行下方

directory populate(directory dir)
{
    path newPath = {.name = "file/", .type = "directory"};
    dir.paths[dir.npaths] = newPath;
    return dir;
}

int seek(directory dir)
{
    populate(dir);
    printf("Should return 0\n");

    // Supposedly accesses memory it shouldn't
    printf("%i\n", strcmp(dir.paths[dir.npaths].type, "directory"));
    return 0;
}

//如果您足够聪明,想翻阅实际的代码,谢谢。

//这是pastebin的链接。 https://pastebin.com/j8y652GD

dir = populate(dir);

也许可以解决您的问题。

如果在populate(dir)行中设置了断点,则执行此行后,您将看到dir保持不变。

因为您的函数填充的参数是struct类型,所以传递给populate的参数正是dir的副本。

dir.paths [dir.npaths] = newPath;

愚蠢的问题,但是您是否在某处为dir.paths[]分配了内存? 如果不是,则必须调用dir.paths = calloc (count, sizeof(path))malloc (count * sizeof(path)) ,效果相同。

就像@code_farmer指出的那样,您传递dir包含的数据以按值populate ,然后将数据复制到堆栈中。 当然,没有人会注意将堆栈上的数据复制回去。 而且没有人应该。 您必须像@code_farmer建议的那样调用populate 而且我甚至建议您在将结构作为参数传递时使用指针,以减少内存占用并在这种情况下使生活更轻松。

hth

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM