我有下面的代码,通过填充0
作为前缀将 IP 地址固定为 15 位。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *function(char *newhost){
char *IPaddr;
IPaddr = (char *)calloc(16, sizeof(char));
size_t i=0 , j= 0;
for(i=0, j=0; j<15; i++, j++){
if((newhost[strlen(newhost)-(i+1)] == '.')){ //////////line 11
if( j == 3 || j == 7 || j == 11){
IPaddr[14-j] = '.';
}else if(j<3){
while(!(j==3)){
IPaddr[14-j]='0';
j++;
}
IPaddr[14-j] = '.';
}else if(j > 3 && j<7){
while(!(j==7)){
IPaddr[14-j]='0';
j++;
}
IPaddr[14-j] = '.';
}else if(j>7 && j<11){
while(!(j==11)){
IPaddr[14-j]='0';
j++;
}
IPaddr[14-j] = '.';
}
}else if(newhost[strlen(newhost)-(i+1)] == '\0'){ ///////////line33
while(!(j==15)){
IPaddr[14-j] = '0';
j++;
}
}else{
IPaddr[14-j] = newhost[strlen(newhost)-(i+1)];
}
}
printf("IPaddr: %s\n", IPaddr);
return IPaddr;
}
int main(int argc,char *argv[]){ /////////line48
char host[100] = {'\0'};
strcpy(host, "10.0.0.2");
char *new_IP;
new_IP = function(host); ////////////line52
printf("newIP:%s\n",new_IP);
free(new_IP);
return 0;
}
该代码有效,编译器既不输出错误也不输出警告。但是,valgrind 输出(valgrind --tool=memcheck --leak-check=yes --track-origins=yes test )
==22544== Conditional jump or move depends on uninitialised value(s)
==22544== at 0x8048547: function (test.c:11)
==22544== by 0x804872B: main (test.c:52)
==22544== Uninitialised value was created by a stack allocation
==22544== at 0x80486DB: main (test.c:48)
==22544==
==22544== Conditional jump or move depends on uninitialised value(s)
==22544== at 0x8048654: function (test.c:33)
==22544== by 0x804872B: main (test.c:52)
==22544== Uninitialised value was created by a stack allocation
==22544== at 0x80486DB: main (test.c:48)
谁能告诉我如何修复代码?