Question

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: enter image description here

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?

Was it helpful?

Solution

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?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top