简体   繁体   中英

Strange character (0010) at the end of string

I'm writing a native app for android using C. Somewhere I want to do a plain old job of getting a substring, which I have wrote a simple C code for it. This is the code:

char* get_part_allocated(const char* src, int start, int len)
{
    LOGI("copying [%s] from [%d] len [%d]\n", src, start, len);
    int nlen = len+1;
    char* alloc = (char*)malloc(nlen*sizeof(char));
    strncpy(alloc, src+start, len);
    LOGI("result is: [%s]\n", alloc);
    return alloc;
}

When I compile and run this code in PC, I get the expected result, but when I run it on android, it always has a strange character at the end which corrupts flow of my program and causes faults!

This is a screenshot of the logcat output: 在此处输入图片说明

I tried padding more NULLs, 2 or even 3, but didn't change anything!

Does someone know what is it and how can I get rid of it?

Neither alloc nor strncpy zero out the newly allocated memory. You need to manually add a zero at the end of your new string.

Possibly you are running this in Debug mode on your desktop, and lots of compilers do zero out newly allocated memory in debug mode (only).

All it needs is this additional line:

alloc[len] = 0;

Note: You don't need to/should not cast malloc in C: Do I cast the result of malloc?

The reason is strncpy doesnt NULL terminate the destination string so your code should look something like below.

strncpy(alloc, src+start, len);
alloc[len]='\0' ;

This should solve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM