0

I need to modify a name of file passing by argument with adding "_out" and changing extension. So, first, I copy the name of old file without extension, like that

  char* arg1 = argv[1];

  char* var1 = NULL;
  var1 = malloc(strlen(arg1) * sizeof(char));
  strcpy( var1, arg1 );
  var1[strlen(var1) - 1] = 'l';
  var1[strlen(var1) - 2] = 'm';
  var1[strlen(var1) - 3] = 'x';

  char* var1Out = NULL;
  var1Out = malloc((strlen(var1) + 4) * sizeof(char));

  strncpy( var1Out, var1, strlen(var1) - 4 ); //Marker


             .
             .
             .

But when I display var1Out with printf just after "//Marker", by passing "test.txt" by argument, I get : "test└" and finally my program return "test└_out.xml" at the end. While when I modify marker line like this:

strncpy( var1Out, var1, strlen(var1) - 3 ); //Marker

it displays:

test.

and with:

strncpy( var1Out, var1, strlen(var1) - 5 ); //Marker

it displays:

tes

so it works perfectly.

Why does it adds a character when I use:

strncpy( var1Out, var1, strlen(var1) - 4 ); //Marker

?

4

2 回答 2

4

在为您分配var1的空间中,您错过了零终止符的空间。利用

malloc(strlen(arg1) + 1)
于 2014-08-12T12:19:04.210 回答
0

复制

如果 source 长于 num,则不会在目标末尾隐式附加空字符。因此,在这种情况下,目的地不应被视为以空结尾的 C 字符串(这样读取它会溢出)。
http://www.cplusplus.com/reference/cstring/strcpy/

这就是为什么我的字符串中有一个附加字符的原因,因为它不被视为以空字符结尾的 C 字符串。

因此,在我的代码中添加:

  var1Out[strlen(var1)- 4] = '\0';

有用。

于 2014-08-14T12:26:05.363 回答