tags:

views:

168

answers:

3

Hi,

I have seen a strange behavior with "strndup" call on AIX 5.3 and 6.1. If I call strndup with size more than the size of actual source string length, then there is a stack corruption after that call.

Following is the sample code where this issue can come:

int main ()
{
    char *dst_str = NULL;
    char src_str[1023] = "sample string";

    dst_str = strndup(src_str, sizeof(src_str));

    free(dst_str);
    return 0;
}

Does anybody have experienced this behavior?

If yes please let me know.

As per my observation, there must be a patch from OS where this issue got fixed. but i could not get that patch if at all there is any. Please throw some light.

Thanks & Regards, Thumbeti

+3  A: 
Alok
A: 

Alok is right. and with the gcc toolchain under glibc, you would need to define _GNU_SOURCE to get the decl of strndup, otherwise it's not decl'd, e.g.:

#include <string.h>
...

compilo:

gcc -D_GNU_SOURCE a.c
jspcal
A: 

Hi,

Thanks a lot for your prompt responses. I have tried the given program.

following is the result:

bash-2.05b# ./mystrndup3
>01234567890123456789012345678<

In my program I have included , still problem is persistent. Following is the strndup declaration in prepossessed code.

extern char * strndup(const char *, size_t);

I would like to clarify one thing, with small program I don't get effect of stack corruption. It is consistently appearing in my product which has huge amount of function calls.

Using strndup in the following way solved the problem:

dst_str = strndup(src_str, srtlen(src_str));

Please note: used strlen instead of sizeof as i need only the valid string. I am trying to understand why it is happening.

Behavior i am seeing with my product when i use strndup with large size:

  1. At the "exit" of main, execution is coring with "illegal instruction"
  2. intermittently "Illegal Instruction" in the middle of execution (after strndup call).
  3. Corrupt of some allocated memory, which is no where related to strndup.

All these issues are resolved by just modifying the usage of strndup with actual size of source string.

Thanks & Regards, Thumbeti

Thumbeti
Please don't post questions in the "answers" section, update your original question instead by "edit"ing it. I have updated my answer, please see that for more information.
Alok
Could it be that your source string is not properly formed and `strndup` is therefore trying to access memory it shouldn't? Although, for that to happen, you must have a badly formed string in source and huge length in the length argument.
Alok