Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

285
Visualizações
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;
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda