0

I encountered a segmentation fault when trying to print an element of an array of c-style strings (at the final iteration i=3). However, I am able to print the same element outside the for-loop.

char* pipe_segments[2];
pipe_segments[0] = "ls";
pipe_segments[1] = "-l";
pipe_segments[2] = "-h";
printf("%s\n", pipe_segments[0]);
printf("%s\n", pipe_segments[1]);
printf("%s\n", pipe_segments[2]);
for(int i = 0; i < 3; i++) {
    printf("%s\n", pipe_segments[i]);
}

Here is the output

ls
-l
-h
ls
-l
Segmentation fault

Why is there a segmentation fault only in the for-loop?

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
qjk
  • 21
  • 1
  • 1
    The code you show isn't really a proper [mre]. It's going to be impossible to replicate the problem with only that code. For example, what is `MAX_PIPE_SEGMENTS`? – Some programmer dude Oct 09 '21 at 09:54
  • Turns out `MAX_PIPE_SEGMENTS` was 2, so `pipe_segments[2]` should be out of bounds. But how was I able assign and access `pipe_segments[2]` before the for-loop? – qjk Oct 09 '21 at 10:00
  • 3
    Do you mean why it doesn't crash executing `pipe_segments[2] = "-h";`? Welcome to the [UB land](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) :) – David Ranieri Oct 09 '21 at 10:03
  • 1
    `"But how was I able assign and access pipe_segments[2] before the for-loop?"` -- The following answer explains it quite well, even if the situation is not exactly the same, as the object you are accessing never existed: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794 – Andreas Wenzel Oct 09 '21 at 10:05
  • 1
    Note that `execve` requires the `argv` array to be `NULL`-terminated, so if you want to pass three arguments, then it needs to have length 4, and you need `argv[3] = NULL;` to terminate the array. Otherwise `execve` has no way of knowing how many arguments are present. – Tom Karzes Oct 09 '21 at 10:07
  • 1
    C doesn't have any kind of bounds-checking, at all. It's up to you as the programmer to make sure you don't access arrays and memory out of bounds. – Some programmer dude Oct 09 '21 at 10:48

0 Answers0