0

My function also returns an integer pointer. I was under the impression that array names are just integer pointers, so that's why i declared it like that. I have made a function called reverse() to reverse a pointer and when i run it on my ubuntu 18.04 with gcc version 7.5, I get a segmentation fault core dumped. Why is this and what is the correct and most efficient code for this?

#include <stdio.h>


int * reverse(int * array, int n){
    int * rev;
    int i = n - 1;
    int j = 0;
    while(i >= 0){
        rev[j] = array[i];
        j++;
        i--;
    }
    return rev;
}

int main(){
    int array[] = {1,2,3,4};
    int * p; //the pointer p that im declaring
    p = reverse(array, 4); //i think this is the segmentation error
    int i = 0;
    printf("the first element is %d", p[0]);
}
  • 3
    `int * rev; rev[j] = array[i];` is undefined behaviour because `rev` is an uninitialised pointer. – kaylum Sep 03 '20 at 11:47
  • 3
    Activate compiler warnings. Use `-Wall -Wextra` and they would have explained the problem – klutt Sep 03 '20 at 11:48
  • oh yes thanks a lot guys! – Zaahir Ahmed Sep 03 '20 at 11:51
  • 1
    BTW the most efficient way to find out what happens in such cases is to use your debugger. Learn how to use it, it will save you countless hours. – Jabberwocky Sep 03 '20 at 11:52
  • 1
    "_ I was under the impression that array names are just integer pointers_" That impression is wrong. Array names _decay_ to pointers in some cases, like when passed to a function, but they are very different things. Array names have size info, whereas pointers lose them. Also, of course if the elements were another type, it won't be `int[]` or `int*`. – underscore_d Sep 03 '20 at 11:59
  • Just single-step through the program using your favourite debugger? They aren't hard to use... – Lundin Sep 03 '20 at 12:58

1 Answers1

1

"I have made a function called reverse() to reverse a pointer and when i run it on my ubuntu 18.04 with gcc version 7.5, I get a segmentation fault core dumped. Why is this?"

The pointer rev in reverse does not point to any memory. You need to allocate memory of n * sizeof(int) and assign rev to point there before dereferencing rev. Else you got undefined behavior accessing unallocated memory.

int * rev = malloc( n * sizeof(int) );
if (!rev)
{
     perror("malloc");
     // error routine.
}