LiorGolan
LiorGolan

Reputation: 375

Why do I get segmentation fault when trying to print an array?

Here's the code:

char* a[] = {"ls", "-l", "|", "grep", "test"};
  int pipe_idx = 2;

  char** ptr2 = a + (pipe_idx * sizeof(char**));
  printf("%s\n", *ptr2);

Basically, this is just a demo code. The program gets the pipe_index (in this case it's 2) and jumps to the right place, and then print it.

Why do I get segmentation fault?

Upvotes: 1

Views: 193

Answers (2)

totoro
totoro

Reputation: 2456

You should do:

char** ptr2 = &a[pipe_idx];

to point at the index (char *) and get the address (char **).

Or even:

char** ptr2 = a + pipe_idx;

+ on pointer is magic. You're effectively exceeding your bounds by multiplying.

Upvotes: 2

SandBag_1996
SandBag_1996

Reputation: 1601

ptr2 is pointing to memory that doesnt belong to you. Right now, it is pointing to a + 8, because sizeof(char**) is sizeof pointer, not the char itself. So the size exceeds your array size. It's UB, and thats why you are getting segfault.

If you are trying to traverse the array using char pointer, you do not need to the multiplication arithmetic as you are doing, you just need to add the pipe_idx to the pointer and it will do the desired arithmetic for you. You need,

char** ptr2 = a + pipe_idx

Upvotes: 3

Related Questions