C 数组结构给出随机段错误 + valgrind 无效写入错误

C array of structure gives random segfault + valgrind invalid write error

当我尝试浏览我的结构数组时,我的代码中出现随机段错误。

我有一个 struct_fd,它包含套接字的值、它的类型、2 个缓冲区和 2 个函数指针。 我还有我的主服务器 "env" 结构 (struct s_sv_prop),它包含指向 struct_fd.

数组的指针

Header :

#define MAX_CLIENTS     10
#define MAX_SOCKETS     1 + MAX_CLIENTS
#define SK_SERV         0
#define SK_CLIENT       1
#define SK_FREE         2

typedef struct s_fd         t_fd;
typedef struct s_sv_prop     t_sv_prop;

struct          s_fd
{
    void    (*ft_read)();
    void    (*ft_write)();
    int     sock;
    int     type;
    char     rd[BUF_SIZE + 1];
    char    wr[BUF_SIZE + 1];
};

struct          s_sv_prop
{
    t_cmd           *cmd;
    t_fd            *fds;
    fd_set          readfds;
    fd_set          writefds;
    int             max;
    int             left;
    int             port;
};

为我的结构数组分配内存的函数:

void                init_sv_prop(t_sv_prop *sv, char *port, char **env)
{
    int             i;

    i = 0;
    sv->max = 0;
    sv->left = 0;
    check_port(port);
    sv->port = (unsigned short) atoi(port);
    sv->cmd = (t_cmd *)malloc(sizeof(*(sv->cmd)));
    init_env(sv, env); /* initiate other env */
    init_command_list(sv); /* malloc an array of another struc */
    sv->fds = (t_fd *)malloc(sizeof(*(sv->fds)) * MAX_SOCKETS);
    while (i < MAX_SOCKETS) {
        clean_fd(&(sv->fds[i]));
        i++;
    }
}

我在 malloc 之后使用 clean_fd 清除所有可能的内存问题:

void        clean_fd(t_fd *fd)
{
    fd->type = SK_FREE; /* Valgrind : Invalid write of size 4 */
    fd->sock = 0;
    bzero(fd->rd, BUF_SIZE + 1);
    bzero(fd->wr, BUF_SIZE + 1);
    fd->ft_read = NULL;
    fd->ft_write = NULL;
}

最终,当我想显示我的结构状态时,我随机出现了一个 EXC_BAD_ACCESS 段错误(虽然不是每次...):

void            sv_socket_state(t_sv_prop *sv, char *tag)
{
    int     i;
    char    *str;
    char    skfr[] = "FREE";
    char    sksv[] = "SERVER";
    char    skcl[] = "CLIENT";

    i = 0;
    while (i < MAX_SOCKETS)
    {
        if (sv->fds[i].type == SK_SERV)
            str = sksv;
        else if (sv->fds[i].type == SK_CLIENT)
            str = skcl;
        else
            str = skfr;
        printf("%5d | %6s | %5d | %6c | %6c\n", i, str, CL_SOCK(i),
            (FD_ISSET(CL_SOCK(i), &sv->readfds) ? 'X' : ' '),
            (FD_ISSET(CL_SOCK(i), &sv->writefds) ? 'X' : ' '));
        i++;
    }
}

当我 运行 我的代码在 OsX 上时,如前所述,我在 运行 最后一个函数时随机出现段错误。 当我 运行 它在 Ubuntu 上时,我得到一个 malloc 错误并且 valgrind 检测到一个无效的写入错误。

我一定错过了我的分配。 您知道问题出在哪里吗?

作为BLUEPIXY said in the , 该行:

sv->fds = (t_fd *)malloc(sizeof(*(sv->fds)) * MAX_SOCKETS);

实际上是:

sv->fds = (t_fd *)malloc(sizeof(*(sv->fds)) * 1 + MAX_CLIENTS);

并导致 malloc 的大小为 *(sv->fds) + MAX_CLIENTS 的值。 宏必须来自:

#define MAX_SOCKETS     1 + MAX_CLIENTS

至:

#define MAX_SOCKETS     (1 + MAX_CLIENTS)

感谢大家的帮助。