Segmentation error when splitting an array containing an IP address

After splitting the IP address, I want to select the last element ie 15 and increase it, but after getting 192 in buff , when it goes to the 1st case, I get a segmentation error!

Why can't he move on? What could 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; } 
+4
source share
2 answers

In your code, in the very first iteration (or, in this case, in any other iteration, except when case 3 hits)

  lastelem=atoi(str5); 

str5 not initialized. therefore it causes undefined behavior .

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

In addition, you do not need to allocate memory for buff , since you are overwriting it with the return pointer from strtok() . This creates a memory leak .

+4
source

Move your str5 stuff inside case3

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

In addition, there is no need to allocate memory for the buff, you do not copy something in it, you just specify something, this will lead to a memory leak in your code.

+2
source

All Articles