J'essayais d'allouer de la mémoire pour mes structures de données (pour obtenir des données à partir de paquets internet), mais j'ai fait face au problème, que mon programme s'arrête juste quand il passe à la deuxième boucle. La première boucle va parfaite et toutes les données, à l'intérieur des structs sont correctes. Voici le code:Realloc arrête le programme sur la deuxième boucle
struct ipOut *ipHeadr = NULL;
struct ipAddr *addrHeadr = NULL;
struct hexOut *hexHeadr = NULL;
struct icmpOut *icmpHeadr = NULL;
struct igmpOut *igmpHeadr = NULL;
struct tcpOut *tcpHeadr = NULL;
struct udpOut *udpHeadr = NULL;
int main() {
ipHeadr = (struct ipOut*)malloc(sizeof(ipHeadr));
addrHeadr = (struct ipAddr*)malloc(sizeof(addrHeadr));
hexHeadr = (struct hexOut*)malloc(sizeof(hexHeadr));
icmpHeadr = (struct icmpOut*)malloc(sizeof(icmpHeadr));
igmpHeadr = (struct igmpOut*)malloc(sizeof(igmpHeadr));
tcpHeadr = (struct tcpOut*)malloc(sizeof(tcpHeadr));
udpHeadr = (struct udpOut*)malloc(sizeof(udpHeadr));
struct sockaddr saddr;
unsigned char *buff = (unsigned char *)malloc(65536);
int sock = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
if (sock < 0){
printf ("Error creating socket");
return 1;
}
int loop = 1;
while (loop == 1){
int saddrLength = sizeof saddr;
rawData = recvfrom(sock, buff, 65536, 0, &saddr, &saddrLength);
printf("raw data %d\n", rawData);
if(rawData <0)
{
printf("Failed to get packets\n");
return 1;
}
gettingPacket(buff, rawData);
}
return 0;
}
void gettingPacket(unsigned char * buff, int data){
packetNum++;
ipHeadr = (struct ipOut*)realloc(ipHeadr, sizeof(ipHeadr)*packetNum);
addrHeadr = (struct ipAddr*)realloc(addrHeadr,sizeof(addrHeadr)*packetNum);
hexHeadr = (struct hexOut*)realloc(hexHeadr, sizeof(hexHeadr)*packetNum);
struct iphdr *iph = (struct iphdr*)buff;
switch (iph -> protocol)
{
case 1:
icmpNum++;
icmpHeadr = (struct icmpOut*)realloc(icmpHeadr, sizeof(icmpHeadr)*icmpNum);
icmpOutput(buff, data);
hexDataOut(buff, data);
break;
case 2:
igmpNum++;
igmpHeadr = (struct igmpOut*)realloc(igmpHeadr,sizeof(igmpHeadr)*igmpNum);
igmpOutput(buff, data);
hexDataOut(buff, data);
break;
case 6:
tcpNum++;
tcpHeadr = (struct tcpOut*)realloc(tcpHeadr,sizeof(tcpHeadr)*tcpNum);
tcpPacketOutput(buff, data);
hexDataOut(buff, data);
break;
case 17:
udpNum++;
udpHeadr = (struct udpOut*)realloc(udpHeadr, sizeof(udpHeadr)*udpNum);
udpPacketOutput(buff, data);
hexDataOut(buff, data);
break;
}
}
Debugging indique que le code cesse sur cette ligne:
ipHeadr = (struct ipOut*)realloc(ipHeadr, sizeof(ipHeadr)*packetNum);
Je pense qu'il ya quelque part est une fuite de mémoire, mais je ne peux pas le trouver.
Hint 'Type * pointeur = malloc (sizeof (* pointeur));', 'sizeof (pointeur)' est la taille du pointeur. 'sizeof (Type)' ou 'sizeof (* pointer)' est la taille du type. – BLUEPIXY
Ne pas lancer le résultat de 'malloc' & amis! – Olaf
Merci, ça marche, je suis idiot. –