c - 使用 strcpy 时打印垃圾

标签 c parsing text malloc strncpy

我有一个函数可以解析一些传入的数据。我的问题是,在使用 strncpy 之后,当我尝试打印它时,我得到了一些垃圾。我尝试使用 malloc 使 char 数组具有精确的大小。

代码:

void parse_data(char *unparsed_data)
{
char *temp_str;
char *pos;
char *pos2;
char *key;
char *data;
const char newline = '\n';

int timestamp = 0;

temp_str = (char*)malloc(strlen(unparsed_data));

g_print("\nThe original string is: \n%s\n",unparsed_data);


//Ignore the first two lines
pos = strchr(unparsed_data, newline);
strcpy(temp_str, pos+1);
pos = strchr(temp_str, newline);
strcpy(temp_str, pos+1);

//Split the line in two; The key name and the value
pos = strchr(temp_str, ':'); // ':' divides the name from the value
pos2 = strchr(temp_str, '\n'); //end of the line
key = (char*)malloc((size_t)(pos-temp_str)-1); //allocate enough memory
data = (char*)malloc((size_t)(pos2-pos)-1);

strncpy(key, temp_str, (size_t)(pos-temp_str));
strncpy(data, pos + 2, (size_t)(pos2-pos));

timestamp = atoi(data);

g_print("size of the variable \"key\" = %d or %d\n", (size_t)(pos-temp_str), strlen(key));
g_print("size of the variable \"data\" = %d or %d\n", (size_t)(pos2-pos), strlen(data));

g_print("The key name is %s\n",key);
g_print("The value is %s\n",data);
g_print("End of Parser\n");
  }

输出:

The original string is: 
NEW_DATAa_PACKET
Local Data Set 16-byte Universal Key
Time Stamp (microsec): 1319639501097446
Frame Number: 0
Version: 3
Angle (deg): 10.228428

size of the variable "key" = 21 or 22
size of the variable "data" = 18 or 21
The key name is Time Stamp (microsec)
The value is 1319639501097446
F32
End of Parser

再次运行:

  The original string is: 
  NEW_DATAa_PACKET
  Local Data Set 16-byte Universal Key
  Time Stamp (microsec): 1319639501097446
  Frame Number: 0
  Version: 3
  Angle (deg): 10.228428

  size of the variable "key" = 21 or 25
  size of the variable "data" = 18 or 18
  The key name is Time Stamp (microsec)ipe 
  The value is 1319639501097446
  F
  End of Parser

最佳答案

你的结果是因为 strncpy 没有在字符串的末尾放置空字符。

关于c - 使用 strcpy 时打印垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11161609/

相关文章:

c - 将十六进制格式的整数数组保存到 char "string"

python - 写从 0 到 1000000000 的数字

java - 在Java中解析CSV文件,如果第一个字段为空,则跳过下一行

java - 从另一个数组的每 5 个元素创建一个 2D 数组

android - 如何在 Android 上的 TextView 中将两行文本居中?

javascript - path.getTotalLength 适用于文本 svg 吗?

c - C 中的符号扩展、二进制加法和减法

c - 多次运行后 memcpy 崩溃

c - 我有两个变量 a=2 b=2 现在我想要 (a + b) *2 并将其存储在 c 变量中

java - 需要帮助解析 Twitter Oauth 的 XML 文件