【问题标题】:Getting segmentation fault because of malloc由于 malloc 导致分段错误
【发布时间】:2017-05-08 20:02:54
【问题描述】:

我目前正在尝试从 Linux 文件“/proc/net/dev”中获取网络接口名称。我有两个问题。首先,我可以通过从第 3 行到文件末尾编写这段代码来获取它:

    char buffer[100], word[10];
    fgets(buffer, 100, fp);
    sscanf(buffer, "%s %*[:] %*s", word);

但问题是我得到带有冒号的字符串(lo:eth0:eth1:)。我怎样才能以我在屏幕上显示的方式获得它们。

第二个问题是为什么我在以下代码中遇到分段错误:

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

#define NETFILE "/proc/net/dev"

static char **interface_names;

int counting_lines()
{
    FILE *fp = fopen(NETFILE, "r");
    int i = 0;
    char buffer[200];

    while (fgets(buffer, sizeof(buffer), fp) != NULL)
    {
        i++;
    }
    fclose(fp);
    return i;
}

void do_malloc()
{
    int i;
    int lines = counting_lines() - 2;

    interface_names = (char **)malloc(lines * sizeof(char *));

    for (i = 0; i < lines; i++)
    {
        interface_names[i] = (char *)malloc(10 * sizeof(char));
    }
}

void free_malloc()
{
    int i;

    for (i = 0; i < (counting_lines() - 2); i++)
    {
        free(interface_names[i]);
    }
    free(interface_names);
}

void get_interface_names()
{
    FILE *fp = fopen(NETFILE, "r");
    int i = -2;
    char buffer[100];

    while (!feof(fp))
    {
        if (i < 0)
        {
            i++;
            continue;
        }
        else
        {
            fgets(buffer, 100, fp);
            sscanf(buffer, "%s %*[:] %*s", interface_names[i]);
            i++;
        }
    }
    fclose(fp);
}

int main()
{
    do_malloc();
    get_interface_names();
    printf("%s\n", interface_names[0]);
    printf("%d\n", counting_lines());
    free_malloc();
    return EXIT_SUCCESS;
}

【问题讨论】:

  • 每个问题一个问题。
  • while (!feof(fp)) 总是无法检测到最后一项。您最终会在列表末尾找到一个重复项。
  • 改用strsep()
  • @EdHeal 如果是这样,你的系统就有大问题了。

标签: c segmentation-fault malloc


【解决方案1】:

您的sscanf 模式错误。应该是:

        sscanf(buffer, " %9[^:] ", interface_names[i]);

开头的空格会跳过行首的任何空格。然后它解析直到下一个: 的所有内容并将其放入interface_names[i],最多允许9 个字符(因为interface_names[i] 是10 个字节)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 2018-12-09
    • 2018-01-02
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多