freeing memory leads to sig fault

R

Ryan Knopp

I can't seem to figure out why this is happening. I even tried to use
gdb but it seems it should work. I've commented below where this is
happening

Here's a snippet.

int main()
{
/* random stuff */

while(1)
{
char mesg[1024];
n = recvfrom(lnd, mesg, 1024, 0, (struct sockaddr *)&cliaddr, &len);
if(n > 0)
{
tmp = parsepacket(mesg);
}
}
}
struct tibo *parsepacket(char packet[])
{
struct tibo *tmp = (struct tibo *)malloc(sizeof(struct tibo));
char **parsed;
char **tmp2;

parsed = nl_to_str(packet);
tmp2 = parsed;
while(*parsed != '\0')
{
if(strncmp("machine", *parsed, 7) == 0)
{
tmp->machine = &parsed[0][8];
parsed[0][7] = '\0';
}
parsed++;
}
/* I tried using the below while loop initially but it failed on the
first iteration. so i just tried to just free tmp2[0] but that failed.
Even trying to free just tmp2 itself fails. Not sure why. */
while(*tmp2 != '\0')
{
free(*tmp2);
tmp2++;
}
free(*tmp2);
return tmp;
}
/* newline to string and string is converted to lowercase */
char **nl_to_str(char packet[])
{
int i, count = 0, j = 0;
char **str;

for(i = 0; packet != '\0'; i++)
if(packet == '\n')
count++;

str = (char **)malloc(count * sizeof(char *));
str[0] = &packet[0];

for(i = 0; packet != '\0'; i++)
if(packet == '\n')
{
packet = '\0';
str[j++] = &packet[i+1];
} else
packet = tolower(packet);

str[j] = '\0';
return str;
}

Thanks in advance
Ryan
 
V

vippstar

I can't seem to figure out why this is happening. I even tried to use
gdb but it seems it should work. I've commented below where this is
happening
<crap C code>
Thanks in advance
Ryan


I am not going to comment every bit of your code, however you assigned
the return value of malloc to tmp and not to *tmp. Why do you free
*tmp?
Why do you return tmp? If the free call succeeded the pointer would be
invalid at this point.

Fixed:

tmp = malloc(size)
if(tmp != NULL) {
/* ... */
}
free(tmp);
return val;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top