djgharphalia07
djgharphalia07

Reputation: 227

Segmentation Fault while Splitting an Array containing IP Address

After splitting the IP address, I want to pick out the last element i.e 15 and increment it but after getting 192 in buff when it goes to 1st case, i get segmentation fault!

Why it can't go further? What may be the problem?

int main(int argc, char** argv) 
{

char str[] = "192.168.10.15"; 
char str1[12];
char *str2, *str3, *str4, *str5;
unsigned char bytes[4];
int i = 0;

int lastelem; 

char* buff = (char *)malloc(20);
buff = strtok(str,".");


while (buff != NULL)
{
   printf("%s\n",buff);

   switch(i)
   {
       case 0: str2=buff;
       break;

       case 1: str3=buff;
       break;

       case 2: str4=buff;
       break;

       case 3: str5=buff;
       break;
   } 

   lastelem=atoi(str5);
   sprintf(str5, "%d",lastelem);

   bytes[i] = (unsigned char)atoi(buff);
   buff = strtok(NULL,".");
   i++;
}
return 0;
}

Upvotes: 4

Views: 103

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

In your code, in the very first iteration, (or, for that case, on any other iteration, except when case 3 is hit)

 lastelem=atoi(str5);

str5 is uninitialized., so it's invoking undefined behaviour.

You should use str5 only after it has been assigned. You can use a flag, if you want, to mark the hit on case 3: or, put the code under the case block itself.

Also, you don't need to allocate memory to buff, as you're overwriting it with the returned pointer from strtok(). That creates a memory leak.

Upvotes: 4

Nishant
Nishant

Reputation: 1665

Move your str5 related stuff, inside case3

case 3: str5 = buff;
lastelem = atoi(str5);
sprintf(str5, "%d", lastelem);
break;

Also, no need to allocate memory to buff, you are not copying something in it, you are just pointing something, this will cause a memory leak in your code.

Upvotes: 2

Related Questions