C array structure gives random segfault error + valgrind invalid entry
I have a random segfault in my code when I try to view my structure array.
I have a struct_fd that contains the socket value, its type, 2 buffers and 2 pointers to work with. I also have my main server "env" structure (struct s_sv_prop) that holds a pointer to the struct_fd array.
Title:
#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;
};
Function where I allocate memory for my structure array:
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++;
}
}
I am using clean_fd to clean up all possible memory problem immediately after malloc:
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;
}
If I want to display the state of my structure, I accidentally get Segfault EXC_BAD_ACCESS (not every time though ...):
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++;
}
}
When I run my code in OsX as mentioned earlier, I accidentally get a segfault when the last function runs. When I run it on Ubuntu, I got a malloc error and valgrind encounters an invalid write error.
I must miss something of my appropriation. Do you have any idea where this problem comes from?
source to share
As BLUEPIXY in the comments, the line:
sv->fds = (t_fd *)malloc(sizeof(*(sv->fds)) * MAX_SOCKETS);
in fact:
sv->fds = (t_fd *)malloc(sizeof(*(sv->fds)) * 1 + MAX_CLIENTS);
and made malloc be of size * (sv-> fds) + MAX_CLIENTS value. The macro should go from:
#define MAX_SOCKETS 1 + MAX_CLIENTS
in
#define MAX_SOCKETS (1 + MAX_CLIENTS)
Thanks everyone for your help.
source to share