【问题标题】:Segmentation Fault while Splitting an Array containing IP Address拆分包含 IP 地址的数组时出现分段错误
【发布时间】:2015-10-29 05:28:00
【问题描述】:

拆分 IP 地址后,我想选择最后一个元素,即 15 并将其递增,但在 buff 中获得 192 后,当它进入第一种情况时,我得到分段错误!

为什么不能走得更远?可能是什么问题?

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;
}

【问题讨论】:

  • discards????哇..
  • see why not to castmalloc()C中的family返回值。
  • @SouravGhosh:总有一天,你关于不投射malloc() 的消息通过!
  • 这个char* buff = (char *)malloc(20); buff = strtok(str,"."); 泄漏了20 字节的内存。此外,您不能为每个作业复制一个数组。
  • sscanf(str,"%d.%d.%d.%d",&n1,&n2,&n3,&n4);

标签: c string pointers split segmentation-fault


【解决方案1】:

在您的代码中,在第一次迭代中,(或者,在这种情况下,在任何其他迭代中,除非case 3 被命中

 lastelem=atoi(str5);

str5 未初始化。因此它正在调用undefined behaviour

只有在分配了str5 之后,您才应该使用它。如果需要,您可以使用标志来标记case 3: 上的命中,或者将代码放在case 块本身下。

另外,您不需要为buff 分配内存,因为您正在使用strtok() 返回的指针覆盖它。这会创建一个memory leak

【讨论】:

  • @DeepJyotiGharphalia 最简单的方法,将所有str5 相关代码移到案例3下...
【解决方案2】:

将与str5 相关的内容移到case3

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

另外,buff不需要分配内存,你不是在复制什么东西,你只是在指向一些东西,这会导致你的代码内存泄漏。

【讨论】:

  • 只要把这行char* buff = (char *)malloc(20);改成char* buff = NULL;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
相关资源
最近更新 更多