E
erbm
Hey people... I'm new in C programing, and i'm having some problem.
What's wrong with the code below. I got no error compiling the file,
but when executing i get a *** glibc detected *** ./test: double free
or corruption (out): 0xbfe83468 *** error:
It's a simple code:
//file config.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
int read_server_list(char *config_file, char **servers)
{
FILE *file;
int i, status;
file = fopen(config_file, "r+");
if(file != NULL)
{
printf("File opened.\n");
status = SUCCESS;
servers = (char **) malloc(MAX_SERVERS * sizeof(char *));
if(servers == NULL)
{
printf("Memory out.\n");
status = OUT_OF_MEM;
}
else
{
for(i = 0; i < MAX_SERVERS; i++)
{
servers = (char *) malloc(MAX_CHAR_LINE);
fgets(servers, MAX_CHAR_LINE, file);
printf("%s",servers); //prints OK
}
}
fclose(file);
}
else
{
printf("Error openig the file.\n");
status = FILE_ERROR;
}
return status;
}
void cleanup_server_list(char **servers)
{
int i = 0;
do {
free( servers );
servers[i++] = NULL;
} while( i < MAX_SERVERS );
free( servers );
servers = NULL;
}
and then
//file main.c
#include <stdio.h>
#include "config.h"
int main()
{
int status;
char *file = "text.txt";
char **servers;
status = read_server_list(file, servers);
cleanup_server_list(servers); // HERE I GET THE ERROR
return 0;
}
What's wrong with the code below. I got no error compiling the file,
but when executing i get a *** glibc detected *** ./test: double free
or corruption (out): 0xbfe83468 *** error:
It's a simple code:
//file config.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
int read_server_list(char *config_file, char **servers)
{
FILE *file;
int i, status;
file = fopen(config_file, "r+");
if(file != NULL)
{
printf("File opened.\n");
status = SUCCESS;
servers = (char **) malloc(MAX_SERVERS * sizeof(char *));
if(servers == NULL)
{
printf("Memory out.\n");
status = OUT_OF_MEM;
}
else
{
for(i = 0; i < MAX_SERVERS; i++)
{
servers = (char *) malloc(MAX_CHAR_LINE);
fgets(servers, MAX_CHAR_LINE, file);
printf("%s",servers); //prints OK
}
}
fclose(file);
}
else
{
printf("Error openig the file.\n");
status = FILE_ERROR;
}
return status;
}
void cleanup_server_list(char **servers)
{
int i = 0;
do {
free( servers );
servers[i++] = NULL;
} while( i < MAX_SERVERS );
free( servers );
servers = NULL;
}
and then
//file main.c
#include <stdio.h>
#include "config.h"
int main()
{
int status;
char *file = "text.txt";
char **servers;
status = read_server_list(file, servers);
cleanup_server_list(servers); // HERE I GET THE ERROR
return 0;
}