2016-07-15 131 views
-3

原谅我的C新手!我试图创建一个接受两个char数组作为参数的函数,并返回一些JSON。这是我的代码,然后是编译警告。该程序在执行时会简单地发生段错误。从C函数返回字符串接受两个字符串

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

char get_json(char *sid, char *obuf) 
{ 
     char *json; 
     json = malloc(strlen(obuf)+37); 
     strcpy(json, "{\"sessionline\":{\"sid\":\""); 
     strcat(json, sid); 
     strcat(json, "\",\"line\":\""); 
     strcat(json, obuf); 
     strcat(json, "\"}}"); 
     return json; 
} 

int main() 
{ 
     char *sid = "xyzxyzxyz"; 
     char *obuf = "asdfasdfasdfasdf"; 
     char *json = get_json(sid, obuf); 
     printf(json); 
} 

当用gcc编译:

test.c: In function ‘get_json’: 
test.c:14:9: warning: return makes integer from pointer without a cast [enabled by default] 
     return json; 
     ^
test.c: In function ‘main’: 
test.c:21:22: warning: initialization makes pointer from integer without a cast [enabled by default] 
     char *json = get_json(sid, obuf); 
        ^
test.c:22:9: warning: format not a string literal and no format arguments [-Wformat-security] 
     printf(json); 
     ^
+0

你忘了''函数的返回类型。 – xinaiz

+0

您可以使用sprintf()简化所有这些功能 – nosbor

+0

看起来像一个错字。 'char get_json(char * sid,char * obuf)'应该是'char * get_json(char * sid,char * obuf)'。注意返回类型的'*'。 – NathanOliver

回答

0

你是返回一个char *为char。

你的函数声明应该是这样的:

char* get_json(char *sid, char *obuf) 

也似乎把更多的东西到json比它可以容纳鉴于其规模。

的段错误发生,因为在从char*char转换的数量被截断为1B,所以printf(json)尝试读取的0之间的存储器一些字节 - 255,它没有先前预留。

+1

Typo问题应该被关闭。你应该投票/标志结束而不是回答。 – NathanOliver

+0

这行不是将* sid和* obuf长度分配给json变量吗? json = malloc(strlen(sid)+ strlen(obuf)+37); 37是静态json的其余部分--sid和obuf将是动态大小。 – Cotton

+0

@Cotton是的,但是在你的问题中,你使用了'malloc(strlen(obuf)+37)' – Annonymus

1
  • get_json应该返回一个指针char*,不char
  • 您忘记了包含sid的分配长度,因此您的程序将导致超出范围的访问并调用未定义的行为
  • 这个程序没有坏处,但一般把用户字符串转换为printf()格式字符串是危险的。

试试这个:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

char get_json(char *sid, char *obuf) 
{ 
     char *json; 
     json = malloc(strlen(sid)+strlen(obuf)+37); 
     if(json == NULL) return json; 
     strcpy(json, "{\"sessionline\":{\"sid\":\""); 
     strcat(json, sid); 
     strcat(json, "\",\"line\":\""); 
     strcat(json, obuf); 
     strcat(json, "\"}}"); 
     return json; 
} 

int main(void) 
{ 
     char *sid = "xyzxyzxyz"; 
     char *obuf = "asdfasdfasdfasdf"; 
     char *json = get_json(sid, obuf); 
     if (json != NULL) fputs(json, stdout); 
} 

或简单的:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

char get_json(char *sid, char *obuf) 
{ 
     char *json; 
     json = malloc(strlen(sid)+strlen(obuf)+37); 
     if(json == NULL) return json; 
     sprintf(json, "{\"sessionline\":{\"sid\":\"" 
       "%s" 
       "\",\"line\":\"" 
       "%s" 
       "\"}}", sid, obuf); 
     return json; 
} 

int main(void) 
{ 
     char *sid = "xyzxyzxyz"; 
     char *obuf = "asdfasdfasdfasdf"; 
     char *json = get_json(sid, obuf); 
     if(json != NULL) fputs(json, stdout); 
} 
+0

感谢您的额外提示。 – Cotton