-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

5
  • 1
    malloc(sizeof(str)); reserves enough memory for a string of 7 characters at most. You probably should change this to malloc(strlen(str)+1);. Commented Jul 14, 2017 at 22:11
  • 6
    1) sizeof(str) is pointer (char *) size. 2) _res doesn't null-terminated. Commented Jul 14, 2017 at 22:11
  • stackoverflow.com/questions/49046/different-sizeof-results Commented Jul 14, 2017 at 22:13
  • @squeamishossifrage although correct its very misleading. you dont say why 7. (or 3). I know why but I had to think about it a bit. Commented Jul 14, 2017 at 22:26
  • It sounds like you want to return a substring. See this, it may help. Commented Jul 14, 2017 at 22:56

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 ?!
every c string must have a '0' at the end, thats the definition of a string in C

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.