在标准C中从字符串中删除字符

5

我正在运行一个(ubuntu precise)linux系统,并且我想在C中从字符串中删除前导字符(制表符)。 我认为以下代码在之前的安装上(ubuntu oneric)有效,但是我现在发现它不再有效了(请注意,这是通用UTF-8字符代码的简化版本):

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

int main()
{

    int nbytes = 10000;
    char *my_line, *my_char;

    my_line = (char *)malloc((nbytes + 1)*sizeof(char));

    strcpy(my_line,"\tinterface(quiet=true):");
    printf("MY_LINE_ORIG=%s\n",my_line);

    while((my_char=strchr(my_line,9))!=NULL){
        strcpy(my_char, my_char+1);
    }
    printf("MY_LINE=%s\n",my_line);

    return 0;
}

I do

gcc -o removetab removetab.c

执行removetab时,我收到以下信息:
MY_LINE_ORIG=   interface(quiet=true):
MY_LINE=interfae(quiet==true):

请注意“=”的重复和“c”的缺失!出了什么问题或我该如何实现替代方案。该代码应支持UTF-8字符串。

1
顺便提一下,你在做很多没有必要的复制,使得这个算法变成了一个类似于O(N!)的东西,而实际上用一个合理的算法可以将其变为O(N)。 - Matteo Italia
2个回答

8
strcpy(my_char, my_char+1);

strcpy的字符串不能重叠。

根据C标准(我强调):

(C99,7.21.2.3p2)“strcpy函数将由s2指向的字符串(包括终止的空字符)复制到由s1指向的数组中。如果在对象之间进行复制并且这些对象重叠,则行为未定义。


3
如果您查看man strcpy
DESCRIPTION
The  strcpy()  function  copies the string pointed to by src, including
the terminating null byte ('\0'), to the buffer  pointed  to  by  dest.
The  strings  may  not overlap, and the destination string dest must be
large enough to receive the copy.

代码在同一数组上调用了 strcpy(),导致字符串损坏。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接