0

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?

Mousa
  • 2,190
  • 3
  • 21
  • 34

2 Answers2

2

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?

Community
  • 1
  • 1
Jongware
  • 22,200
  • 8
  • 54
  • 100
  • Oops! The same old mistake that won't stop catching developers :D Thank you. – Mousa Nov 09 '13 at 16:18
  • And thank you about the note, but ndk gives an error when I don't cast it: "In function 'char* get_part_allocated(char const*, int, int)': error: invalid conversion from 'void*' to 'char*' [-fpermissive]" I think it may be that ndk is using c++ compiler, right? – Mousa Nov 09 '13 at 16:22
  • 1
    Correct, the cast is optional (and unnecessary) in C but *mandatory* for C++. It may mean, though, that you are compiling your .c as if it is .cpp instead. As you see, it has this relatively unharmful side effect but there may be others. Check if you can force your compiler to use C for .c and C++ for .cpp files. – Jongware Nov 09 '13 at 18:40
1

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.

Sagar Masuti
  • 1,271
  • 2
  • 11
  • 30
  • Thank you Sagar, yes that was the problem, since I misunderstood the docs and thought the function will do that for me. – Mousa Nov 09 '13 at 16:24