2
Hello guys! I am implementing a code to insert a kind of table into a pointer and relocate memory while the function add()
is being executed, the function name()
will be executed only once to set the table name.
The error: when adding two names to the table, the code performs normally, but when I exceed two calls to the function add()
, there occurs a Segmentation.
Error example:
add(table, "Lucas\n");
add(table, "Vanessa\n");
add(table, "Marcos\n");
Complete code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int name(char *table, char *text)
{
table = (char *) realloc(table, (strlen(text) + 1) * sizeof(char));
if (table == NULL) {
return EXIT_FAILURE;
}
/* O nome da tabela é copiado para "table" */
strncpy(table, text, (strlen(text) + 1) * sizeof(char));
return EXIT_SUCCESS;
}
int add(char *table, char *text)
{
table = (char *) realloc(table, (strlen(text) + 1) * sizeof(char));
if (table == NULL) {
return EXIT_FAILURE;
}
/* Os dados da tabela são concatenados */
strncat(table, text, (strlen(text) + 1) * sizeof(char));
return EXIT_SUCCESS;
}
int main(void)
{
char *table = (char *) malloc(sizeof(char));
if (table == NULL) {
fprintf(stderr, "Erro ao inicializar o ponteiro!\n");
exit(EXIT_FAILURE);
}
name(table, "Nomes:\n");
add(table, "Lucas\n");
add(table, "Vanessa\n");
printf("%s", table);
free(table);
return EXIT_SUCCESS;
}
From now on, thank you very much! :)
Caracaaa, I went unnoticed! Thank you very much, bro :D I really thought that the realloc() function matched the size of the previously allocated string, but it’s wrong that we learned. Big hug, my brother! :)
– Lucas Araújo