-3

This function make a strange error after using it several times and I really can't understand the reason behind it.

    char *get_range(char *str,int min,int max){
    char *_res=(char *)malloc(sizeof(str));
    int cur=0;
    while (min<max){
        _res[cur]=str[min];
        min++;
        cur++;
        }
    return _res;
    }

The problem is that after using this function several times, the output comes with additional chars and I don't understand why.

Notice: The additional chars are allway used returned by the function beffor

melpomene
  • 84,125
  • 8
  • 85
  • 148

1 Answers1

2
  char *_res=(char *)malloc(sizeof(str));

is wrong. sizeof(str) is measuring the size of a char pointer. This is either 4 or 8 (typically) depending on your system (32 or 64 bit).

You need

char *_res=(char *)malloc(strlen(str) + 1);

strlen returns the number of characters in the string, and you need to add 1 for the terminating 0;

Second you have to add a terminating zero at the end, do:

_res[cur] = '\0'; 

before returning

pm100
  • 48,078
  • 23
  • 82
  • 145
  • Really thank you ....i have another question if i am working on a array of strings......I should add the terminating char manually to every string is this true ?! – Aly Mohamed Jul 15 '17 at 10:48
  • every c string must have a '0' at the end, thats the definition of a string in C – pm100 Jul 16 '17 at 22:36