Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Quero saber se há algum erro na função testToString eu não estou conseguindo visualizar.
Trecho adaptado do código
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
#define BUFFER_LITLE 1024
typedef struct _LinkedListNode LinkedListNode;
typedef struct _Pessoa Pessoa;
typedef char * String;
typedef void * Generic;
struct _LinkedListNode {
Generic content;
LinkedListNode* next;
};
struct _Pessoa {
String nome;
int idade;
};
String pessoaToString(Generic a) {
String cache = NULL;
Pessoa *p = (Pessoa *) a;
int length = 0;
if (p == NULL) return NULL;
length = sizeof (*cache) * 256
cache = (String) malloc(length);
memset(cache, '\0', length);
sprintf(cache, "Pessoa: Nome=\"%s\", Idade=\"%d\"\n", p->nome, p->idade);
return cache;
}
String testToString(LinkedListNode n, String(*toString)(Generic)) {
String cache = NULL;
String v1 = NULL;
String v2 = NULL;
int length = BUFFER_LITLE;
if (n == NULL || toString == NULL) return NULL;
if ((v1 = testToString(n->next, toString)) != NULL) {
length += (strlen(v1) + 1);
}
if ((cache = (String) malloc((sizeof *cache) * length)) == NULL) {
perror("malloc");
if (v1 != NULL) {
free(v1);
}
return NULL;
}
memset(cache, '\0', length);
v2 = toString(n->content);
if (v1 != NULL) strncat(cache, v1, (length - BUFFER_LITLE));
if (v2 != NULL) strcat(cache, v2);
if (v1 != NULL) free(v1);
if (v2 != NULL) free(v2);
return cache;
}
int main(int argc, char** argv) {
LinkedListNode l = NULL;
/*
* Supondo que já exista uns 3000 LinkedListNode l
e que cada LinkedListNode->content tenha um "Pessoa "
*/
fprintf(stdout, "%s", testToString(l, pessoaToString));
return (EXIT_SUCCESS);
}
Estou com o seguinte problema: O programa está terminando com SIGABRT exatamente nessa função, está dando erro em strlen(Invalid read of size 1) e erro no strncat (Invalid read of size 1) quando eu uso o valgrind.
Obrigado.
Carregando comentários...