int GetStrInBuf( char *profile, char *KeyName, char *KeyVal, int type) { char buf[512] = {0}; FILE *fp; char docat[128] = {0}; long profilelen; sprintf(docat, "nohup cat %s -> %s 0</dev/null", profile, TEMPTXT); system__popen(docat, NULL, 0); //printf("%s\n",docat); if( (fp=fopen( TEMPTXT,"r" ))==NULL ){ printf( "openfile [%s] error [%s]\n", profile, strerror(errno) ); return -1; } fseek(fp, 0, SEEK_END); profilelen = ftell(fp); fseek( fp, 0, SEEK_SET); fread(buf, 1, profilelen, fp); fclose(fp); char *json_str = (char *)malloc(strlen(buf)); strcpy(json_str, buf); struct json_object* json_obj = json_tokener_parse(json_str); // printf("Age: %d\n", json_object_get_int(json_object_object_get(json_obj, "age"))); memset(buf, 0x00, sizeof(buf)); if(type == 0) { strcpy(buf, json_object_get_string(json_object_object_get(json_obj, KeyName))); if(strlen(buf) == 0) { memset(KeyVal, 0x00, sizeof(KeyVal)); } else{ snprintf(KeyVal, (strlen(buf)+1), "%s", buf); printf("name:%s,valye:%s\n", KeyName, KeyVal); } } else { int str_value = json_object_get_int(json_object_object_get(json_obj, KeyName)); sprintf(KeyVal,"%d", str_value); printf("name:%s,valye:%s\n", KeyName, KeyVal); } memset(json_str, 0x00, sizeof(json_str)); free(json_str); json_object_put(json_obj); return 0; } int test(){ char buf_d[64]; memset(buf_d, 0x00, sizeof(buf_d)); GetStrInBuf(VTMP_JSON_CELL_INFO, "ipv4", buf_d, 0); char buf_a[64] = ""; memset(buf_a, 0x00, sizeof(buf_a)); GetStrInBuf(VTMP_JSON_CELL_INFO, "ipv6", buf_a, 0); if(strlen(buf_a) > 0) { char buf_c[128] = ""; memset(buf_c, 0x00, sizeof(buf_c)); sprintf(buf_c, "%s,%s",buf_d, buf_a); set_config_value(DATE_FILE,"gw5GIp",buf_c); } else{ set_config_value(DATE_FILE,"gw5GIp",buf_d); } printf("aa\n"); return 0; }
时间: 2024-03-20 15:43:53 浏览: 119
keyname:键盘事件键名实用程序
在代码中,我发现以下两行可能会导致段错误:
```
char *json_str = (char *)malloc(strlen(buf));
strcpy(json_str, buf);
```
这是因为 `malloc` 函数分配的内存大小应该为字符串长度加上1(用于存储字符串结束符 `\0`),因此应该改为:
```
char *json_str = (char *)malloc(strlen(buf) + 1);
strcpy(json_str, buf);
```
此外,还有一处问题可能会导致段错误:
```
memset(json_str, 0x00, sizeof(json_str));
```
这是因为 `json_str` 是指针类型,`sizeof(json_str)` 返回的是指针类型的大小,而不是指向的内存空间的大小。应该改为:
```
memset(json_str, 0x00, strlen(json_str) + 1);
```
这两处问题都涉及到了内存的操作,如果内存操作不当,就容易导致段错误。
阅读全文