Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of # symbol in C

Tags:

c

I'm taking on an online C language test (not for a job, just for on my own) and I keep running into questions of this type using the hash symbol. I am assuming its not a typo and I am not familiar with this use of a hash symbol.

#include <stdio.h>
int* func()
{
    int num = 10;
    return #
}
int main()
{
    int *ptr = func();
    printf("%d\n", *ptr);
    return 0;
}

What is the output of the above C code?

The answer is that it is a runtime error and the explanation is

The variable defined in a function will be allocated in stack segment, which will be removed when the function returns. So accessing the address of those variables results in segmentation fault.

like image 585
Richard Johnson Avatar asked Nov 29 '22 13:11

Richard Johnson


1 Answers

Whoever created the test didn't properly encode their HTML. What they wanted that line to look like is:

return &num;

They put that directly into the HTML of the test page, forgetting that &XXX; is how HTML entities are entered. &num; is the entity for the # character. They should have written:

return &amp;num;

&amp; is the entity for the & character.

like image 88
Barmar Avatar answered Dec 19 '22 22:12

Barmar