-7

I got an surprising observation, the following code is getting a Segmentation Fault

#include<stdio.h>
void main() {
    int *i;
    *i = 100;
    printf("%u\n",i);
    printf("%d\n",*i);
}

But not the below one.

#include<stdio.h>
void main() {
    char* str;
    int *i;
    *i=100;
    str = "Hello";
    printf("%u\n",i);
    printf("%s %d\n",str,*i);
}

Can Someone explains the behavior? I'm using gcc.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

3 Answers3

1

First of all, both the snippets cause undefined behavior because of the dereference of uninitialized pointer i.

In your first case, you're trying to dereference an uninitialized pointer i, so that is undefined behavior.

You're doing

 *i = 100;

but think, where does i point to? Probably to some memory location which is not accessible from the process, so it is invalid memory access. This triggers the UB.

Same in the second snippet, too.

However, if you remove the usage of i from the second snippet, it will be OK.

After the proposed change, in the second snippet, you're storing the starting address of the string literal into the pointer variable, i.e, assigning it. So, it is perfectly OK.

For a statement like

  str = "Hello";

you're not defererencing str here, rather, assigning a pointer value to str, which is perfectly fine.


That said,

  • according to the C standard, for a hosted environment, void main() is not a conforming signature, you must use int main(void), at least.
  • A statement like printf("%u\n",i); also invokes undefined behaviour in it's own way. In case you want to print the pointer, you must use the %p format specifier and cast the argument to void*.
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Your both programs will cause undefined behavior because of following reasons.So will not get the correct result.

1) Dereferencing uninitialized pointer *i = 100; is undefined behavior . In your both examples you are dereferencing pointer i before initializing it. Therefore first initialize pointer using & operator and after use it in your code.

2) Printing a pointer value using the conversion specifier for an unsigned. You should use %p instead.

MCG
  • 1,011
  • 1
  • 10
  • 21
0

i has not been initialized to point to any memory location in particular, so it is not a valid pointer value. Attempting to write through an invalid pointer leads to undefined behavior, meaning the result can be anything - your code may crash outright, it may corrupt data, it may have garbled output, or it may appear to work with no issues.

John Bode
  • 119,563
  • 19
  • 122
  • 198