0

I have the code bellow that keeps giving this error "dereferencing a null pointer" but the pointer is not supposed to be null

char* foo(char* str, int* x) {
    *x = strlen(str);
    char* str2 = malloc((*x+1)*sizeof(char));
    for (int i = 0; i < *x; i++)
        str2[i] = str[*x - i];//I get the error here for str2
return str2;
}

I have tried print sizeof(str2) but it always says 4 no matter how much memory I allocate so, what is the problem and how can i solve it? this is how i call the function:

int main()
{
    char* str = "hello";
    int l=1;
    foo(str,&l);
    return 0;
}
Raea6789
  • 141
  • 1
  • 11

0 Answers0