我使用cJSON
与JNI结合在我的Java和C组件之间来回传递JSON数据。C字符串有随机尾随字符,空终止问题?
我是C新手,自学自学,请耐心等待。
cJSON
有一个不错的功能,cJSON->Print
,它将JSON结构转换成字符串表示。这很好,除了字符串是“JSON漂亮”格式,所有换行符和制表符都保持不变。我不需要其中的任何一个,因为我的应用程序不显示JSON,只是将它用于数据传输。所以,我试图编写一个函数来删除这些多余的字符。
void json_clean(char *buffer, const char *pretty) {
int count = 0;
for(int i = 0; i < strlen(pretty); i++) {
if(pretty[i] == '\n' || pretty[i] == '\t')
continue;
buffer[count] = pretty[i];
count++;
}
int last = strlen(buffer) - 1;
buffer[last] = '\0';
}
这将有效消除\n
和\t
字符就好了,但有时最后我得到一些垃圾字符,如6
或?
,这使我觉得这是一个空终止的问题。
在C中使用printf
并以Java打印出来时,字符串出现方式相同。
我一定比我更需要的NUL
字符之前我调用该函数分配了一个多字节:
// get the pretty JSON
const char *pretty = cJSON_Print(out);
// how many newlines and tabs?
int count = 0;
for(int i = 0; i < strlen(pretty); i++) {
if(pretty[i] == '\n' || pretty[i] == '\t')
count++;
}
// make new buffer, excluding these chars
char *newBuf = malloc((strlen(pretty) - count) + 1); // +1 for null term.
json_clean(newBuf, pretty);
// copy into new Java string
jstring retVal = (*env)->NewStringUTF(env, newBuf);
free(newBuf); // don't need this anymore
任何帮助是极大的赞赏。
要添加到@兴的评论,问题是,'newBuf'没有初始化,所以'strlen'通话读取随机数据和下车步行到区域的不应该。如果你在使用之前将内存置零,那么你会很好,但@ xing的回应是更好的解决方案。 – DocMax