2

In below code , I have been facing some unusual behavior of strtol function as it doesn't return the last value associated with string passed as a 2nd parameter to the expcmp function. I don't see same behavior with first string .

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int16_t  expcmp( char* exp_cmp,char* exp_val)
{

    char DELIM='.';

    int16_t rc=1;

    char *p=NULL;
    char *temp=NULL;
    if(strlen(exp_cmp)>0)
        {
            p=(char*)malloc(sizeof(strlen(exp_cmp)+1));
            strcpy(p,exp_cmp);
            printf("p=%s\n",p);
        }
    if(strlen (exp_val)>0)
        {
            temp=(char*)malloc(sizeof(strlen(exp_val)+1));

            strcpy(temp,exp_val);
            printf("temp=%s\n",temp);
        }

    while (*temp) {
        if (isdigit(*temp)) {
            int16_t val = strtol(temp, &temp, 10);
            printf("temp=%d\n",val);
        }
        else if(*temp!=DELIM)
            {
                rc=0;
                break;
            }
        temp++;
    }

    while (*p) {
        if (isdigit(*p)) {
            int16_t val = strtol(p, &p, 10);
            printf("val=%d\n",val);
        }
        else if(*p!=DELIM)
            {
                rc=0;
                break;
            }
        p++;
    }

    return rc;

}

int main()
{
    int ret_code;
    ret_code=expcmp(".1.7.8.29.41.8153",".1.7.8.29.41.8153");
    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
user2997518
  • 812
  • 6
  • 17
  • You have a memory leak because you never `free(temp)`. And you can't do this because `strtol` modifies `temp`. – Barmar Dec 26 '14 at 03:22
  • 2
    Don't cast malloc: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Barmar Dec 26 '14 at 03:39

1 Answers1

3

You're not allocating enough space for the strings. You shouldn't use sizeof(strlen(...)+1), just use strlen(...)+1.

        p=malloc(strlen(exp_cmp)+1);
        temp=malloc(strlen(exp_val)+1);

sizeof(strlen(...)+1 is just the size of a size_t value (probably 8 bytes), not the length of the string you're going to copy. So the strings you're allocating are not long enough, and when you do the strcpy() you're overflowing the strings. This results in undefined behavior.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, and nice hat. I just discovered that you can turn, move and resize them to fit your picture. – Mad Physicist Dec 26 '14 at 03:55
  • Thanks it works. I did the same for both strings but one was working properly and other one was not , so couldn't guess the same.I believe compiler needs to be smart enough to take care of this kind of issue by flashing the warnings. – user2997518 Dec 26 '14 at 04:00
  • C doesn't do bounds checking for you. The programmer is supposed to be smart enough to allocate the correct space. – Barmar Dec 26 '14 at 04:01