How to remove first character from C-string?

后端 未结 7 1214
小鲜肉
小鲜肉 2021-02-04 01:52

Can anyone please help me? I need to remove the first character from a char * in C.

For example, char * contents contains a \'\\n\'

7条回答
  •  感情败类
    2021-02-04 02:15

    Do not just increment the pointer if you have malloc'd any memory or your program will crash. free needs the original pointer. You can copy the pointer, make a new chunk of memory and memcpy it, access it as ptr+1 or any of a bunch of other ways, but the people who say just increment the pointer are giving you dangerous advice. You can run this sample program and see what happens when you "just increment the pointer".

    #include 
    #include 
    #include 
    int main(void)
    {
        char *str = (char *)malloc(10);
        strcpy(str, "1234567890");
        printf("%s\n", str);
        str++;
        printf("%s\n", str);
        free(str);
    }
    

    Hint: Here's the result:

    [mfisch@toaster ~]$ ./foo
    1234567890
    234567890
    *** glibc detected *** ./foo: free(): invalid pointer: 0x08c65009 ***
    ======= Backtrace: =========
    /lib/tls/i686/cmov/libc.so.6(+0x6b591)[0x724591]
    /lib/tls/i686/cmov/libc.so.6(+0x6cde8)[0x725de8]
    /lib/tls/i686/cmov/libc.so.6(cfree+0x6d)[0x728ecd]
    ./foo[0x80484e3]
    /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0x6cfbd6]
    ./foo[0x80483f1]
    ======= Memory map: ========
    001c9000-001e4000 r-xp 00000000 08:01 2883609    /lib/ld-2.11.1.so
    001e4000-001e5000 r--p 0001a000 08:01 2883609    /lib/ld-2.11.1.so
    001e5000-001e6000 rw-p 0001b000 08:01 2883609    /lib/ld-2.11.1.so
    006b9000-0080c000 r-xp 00000000 08:01 3015690    /lib/tls/i686/cmov/libc-2.11.1.so
    0080c000-0080d000 ---p 00153000 08:01 3015690    /lib/tls/i686/cmov/libc-2.11.1.so
    0080d000-0080f000 r--p 00153000 08:01 3015690    /lib/tls/i686/cmov/libc-2.11.1.so
    0080f000-00810000 rw-p 00155000 08:01 3015690    /lib/tls/i686/cmov/libc-2.11.1.so
    00810000-00813000 rw-p 00000000 00:00 0
    00e4d000-00e4e000 r-xp 00000000 00:00 0          [vdso]
    00fe0000-00ffd000 r-xp 00000000 08:01 2883667    /lib/libgcc_s.so.1
    00ffd000-00ffe000 r--p 0001c000 08:01 2883667    /lib/libgcc_s.so.1
    00ffe000-00fff000 rw-p 0001d000 08:01 2883667    /lib/libgcc_s.so.1
    08048000-08049000 r-xp 00000000 08:01 9700477    /home/mfisch/foo
    08049000-0804a000 r--p 00000000 08:01 9700477    /home/mfisch/foo
    0804a000-0804b000 rw-p 00001000 08:01 9700477    /home/mfisch/foo
    08c65000-08c86000 rw-p 00000000 00:00 0          [heap]
    b7600000-b7621000 rw-p 00000000 00:00 0
    b7621000-b7700000 ---p 00000000 00:00 0
    b776f000-b7770000 rw-p 00000000 00:00 0
    b7780000-b7783000 rw-p 00000000 00:00 0
    bfc22000-bfc37000 rw-p 00000000 00:00 0          [stack]
    Aborted
    

提交回复
热议问题