0

I wrote this code to accept a string and until where it should extract a string and print it. Given below is the code:

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

int strlen(char s[]){
    int i = 0;
    while(s[i]!='\0')
        i++;
    return i;
}

char *extract(char s[], int n){
    char *result = (char *)malloc(sizeof(char)*3);
    for(int j=0;j<n;j++){
        result[j]=s[j];
    }
    return result;
}

int main(){
char str[100];
int till;
printf("Enter a string: ");
scanf("%s", str);

printf("Until where to extract: ");
scanf("%d", till);

char *ret = extract(str, till);

printf("%s is extracted", ret);

return 0;
}

This is what happens:

Enter a string: hello
Enter from where to extract: 2

And then it crashes. I don't see what the problem is.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Rahul
  • 69
  • 2
  • 12

3 Answers3

1

At very first, you need to change

scanf("%d", till);

to

scanf("%d", &till);

as scanf() needs a pointer to the data type argument for the supplied format specifier. Using a wrong type of argument causes undefined behavior.

Then, there are many issues, like

  1. You're allocating only 3 chars, where you're looping based on the incoming value of n.
  2. You never checked for the success of malloc().
  3. You're not null-terminating your result which you intend to use as a string later.

That said,

  1. You should always limit the input for your strings to avoid the possibility of overrun, like

    scanf("%99s", str);  //considering the length of the array is 100.
    
  2. There is a library function strlen() available with string.h. Even if you want to roll out your own functions, try to follow a different naming convention.

  3. You did not free() the allocated memory.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

I you add -Wall to command when you compile your code you'll see

test.c:40:2: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
  scanf("%d", till);
  ^

Then change you must change it to scanf("%d", &till);

LPs
  • 16,045
  • 8
  • 30
  • 61
0

In addition to the other suggestions:

char *result = (char *)malloc(sizeof(char)*3);

Should be:

char *result = malloc(n + 1);
keithmo
  • 4,893
  • 1
  • 21
  • 17