你能告诉我这段代码有什么问题:
#include <stdio.h>
#if __STDC_VERSION == 199901L
#include <stdint.h>
#include <string.h>
#else
/* change to fit the compiler */
typedef unsigned char uint8_t;
typedef unsigned long uint32_t;
#endif
#define IPV4
#if defined(IPV4)
#define NBYTES 4
#elif defined(IPV6)
#error IPV6 not supported
#else
#error No valid IP version protocol defined
#endif
char* concat(char *s1, char *s2)
{
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
//in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
int main()
{
uint32_t ipAddress = 167840383;
uint8_t octet[NBYTES];
int x;
char buffer[4];
char buffer2[100];
for (x = 0; x < NBYTES; x++)
{
octet[x] = (ipAddress >> (x * 8)) & (uint8_t)-1;
}
for (x = NBYTES - 1; x >= 0; --x)
{
// sprintf("%d", octet[x]);
sprintf(buffer2, "%d", octet[x]);
// if (x > 0) printf(".");
if (x > 0) {
char * temp = concat(buffer2, ".");
strcpy(buffer2, temp);
}
}
sprintf("\n%s", buffer2);
return 0;
}
我正在尝试将此代码重写为一个函数,该函数连接IP的每个部分,使用sprintf从32位整数到buffer2 char变量,并返回带有十进制表示IP的转换字符串,但是我正在运行已编译的应用程序它打印错误:“总线错误:10”。
调试信息如下:
MacBook-Air-Pavel:gamind paus$ gcc -o int2ip int2ip.c
int2ip.c:21:20: warning: implicitly declaring library function 'malloc' with type 'void *(unsigned long)'
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
^
int2ip.c:21:20: note: please include the header <stdlib.h> or explicitly provide a declaration for 'malloc'
int2ip.c:21:27: warning: implicitly declaring library function 'strlen' with type 'unsigned long (const char *)'
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
^
int2ip.c:21:27: note: please include the header <string.h> or explicitly provide a declaration for 'strlen'
int2ip.c:23:5: warning: implicitly declaring library function 'strcpy' with type 'char *(char *, const char *)'
strcpy(result, s1);
^
int2ip.c:23:5: note: please include the header <string.h> or explicitly provide a declaration for 'strcpy'
int2ip.c:24:5: warning: implicitly declaring library function 'strcat' with type 'char *(char *, const char *)'
strcat(result, s2);
^
int2ip.c:24:5: note: please include the header <string.h> or explicitly provide a declaration for 'strcat'
int2ip.c:50:21: warning: format string is not a string literal (potentially insecure) [-Wformat-security]
sprintf("\n%s", buffer2);
^~~~~~~
/usr/include/secure/_stdio.h:47:56: note: expanded from macro 'sprintf'
__builtin___sprintf_chk (str, 0, __darwin_obsz(str), __VA_ARGS__)
^
5 warnings generated.
我不知道为什么。你能帮帮我吗?
答案 0 :(得分:1)