0
你能告訴我什麼是錯,此代碼:總線Mac上的錯誤10,而串聯設置的字符
#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.
我不知道爲什麼。你可以幫幫我嗎?
你能調試並告訴我們在哪一行出現錯誤嗎? – wimh 2015-02-24 10:52:36
您顯示的輸出不是調試信息,而是編譯器輸出。請閱讀並遵循以下建議:包括''和''。你不是在這裏過分複雜嗎?您的結果最多可以爲24個字符(對於IP6,包括終止空字符),因此不需要動態分配。此外,沒有'free'的分配會引入內存泄漏。 –
2015-02-24 11:15:04