user1974753
user1974753

Reputation: 1457

Segmentation fault when jumping to label

Hey the following code is driving me crazy and is giving me a segmentation fault when I run it. Note I am using first class labels here.

#include <stdio.h>

main()
{
   static void* array[] = {&&label2, &&label1};
   void* programCount = array;

   goto *programCount++;


   label2: ;
     int b = 100;
     printf("%d\n", b);

   label1: ;
     int b2 = 1000;
     printf("%d\n", b2);
}

I can't see why this is happening, it compiles fine...

Upvotes: 0

Views: 610

Answers (2)

Andreas Fester
Andreas Fester

Reputation: 36649

This question refers to a gcc extension, Labels as Values.

The code from the question compiles fine, although it gives a lot of warnings when compiled with -Wall -pedantic. I suppose the issue is with the assignment to the void* pointer. The following code works well:

static void* array[] = {&&label2,&&label1};

goto *array[0];

As @ouah writes, the type of your void pointer is wrong. When you are using void**, then the following also works:

void** programCount = array;

goto *programCount[0];
// or goto *programCount[1];

And, finally, to reflect the code from your question, you can also use

void** programCount = array;

goto **(++programCount);

to jump to the second label in the array (label1). Note that you need to use pre-increment to increment the pointer before evaluating its value.

Disclaimer: I am not in favor of using labels or goto in C or C++. There are other language elements which provide a more suitable solution to such problems, e.g. as @jweyrich wrote arrays of pointer-to-functions. Since this is non-portable, it should not be used in real life applications (if I was the code reviewer, it would not get through the review ;-) )

Upvotes: 3

ouah
ouah

Reputation: 145919

The type of programCount is not correct, use void **:

void **programCount = array;

then you need to dereference programCount twice like:

goto *programCount[0];

to jump to the label label2, or

goto *programCount[1];

to jump to the label label1.

Here the && operator is the GNU C label address operator.

Upvotes: 1

Related Questions