Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Following C code compiles and runs, but is it undefined bahaviour?

I posted a question about some pointer issues I've been having earlier in this question: C int pointer segmentation fault several scenarios, can't explain behaviour

From some of the comments, I've been led to believe that the following:

#include <stdlib.h>
#include <stdio.h>
int main(){
   int *p;
   *p = 1;
   printf("%d\n", *p);
   return 0;
}

is undefined behaviour. Is this true? I do this all the time, and I've even seen it in my C course. However, when I do

#include <stdlib.h>
#include <stdio.h>
int main(){
   int *p=NULL;
   *p = 1;
   printf("%d\n", *p);
   return 0;
}

I get a seg fault right before printing the contents of p (after the line *p=1;). Does this mean I should have always been mallocing any time I actually assign a value for a pointer to point to?

If that's the case, then why does char *string = "this is a string" always work?

I'm quite confused, please help!

like image 212
P. Gillich Avatar asked Dec 09 '22 23:12

P. Gillich


1 Answers

This:

int *p;
*p = 1;

Is undefined behavior because p isn't pointing anywhere. It is uninitialized. So when you attempt to dereference p you're essentially writing to a random address.

What undefined behavior means is that there is no guarantee what the program will do. It might crash, it might output strange results, or it may appear to work properly.

This is also undefined behaivor:

int *p=NULL;
*p = 1;

Because you're attempting to dereference a NULL pointer.

This works:

char *string = "this is a string" ;

Because you're initializing string with the address of a string constant. It's not the same as the other two cases. It's actually the same as this:

char *string;
string = "this is a string";

Note that here string isn't being dereferenced. The pointer variable itself is being assigned a value.

like image 176
dbush Avatar answered Dec 31 '22 01:12

dbush