-4

When I compile the following code and run it the code runs

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(){
    char* array[1];
    scanf("%s",array[0]);
    return 0;
}

but the following code doesn't run. It shows segmentation fault. Whats the reason.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(){
    char* array[2];
    scanf("%s",array[0]);
    scanf("%s",array[1]);
    return 0;
}

My input is bond in 1st case and James Bond in 2nd

  • 2
    Both are UB as `array[]` is not initialized/assigned. – chux - Reinstate Monica Jul 10 '17 at 16:31
  • Wrong data type. You want char [], not char *[]. Make sure the array has room for the input data, and limit the number of characters you read. char line[1024]; fgets(line, sizeof line, stdin); is one, easy way. – Bjorn A. Jul 10 '17 at 16:32
  • PS: The first version works by luck only. The array allocates room for 1 pointer (4 or 8 bytes, typically). Try serving the program a string longer than 8 bytes, and then try to print it. ;) – Bjorn A. Jul 10 '17 at 16:34
  • Possible duplicate of [What is a segmentation fault?](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) – Chris Turner Jul 10 '17 at 16:38
  • @chux if we do char *array[2]; array[0] = "my"; array[1] = "name"; It also works. I am doing the same thing using scanf? – Sahil Kumar Jul 10 '17 at 16:42
  • 2
    @SahilKumar `char *array[2]; array[0] = "my";scanf("%s",array[0]);` is another form of UB. Why have you not posted your input? – chux - Reinstate Monica Jul 10 '17 at 16:44
  • @SahilKumar there is a huge difference between `array[0] = "my";` and `scanf("%s", array[0])`. Infact there is nothing similar in them. – Ajay Brahmakshatriya Jul 10 '17 at 16:49
  • @BjornA no! Your explanation is not correct. He is passing `array[0]` not `&array[0]`. Even for strings less than 8 length it is UB because `array[0]` is uninitialised. – Ajay Brahmakshatriya Jul 10 '17 at 16:52
  • @AjayBrahmakshatriya You're right. Thanks for the correction. :) – Bjorn A. Jul 10 '17 at 16:54
  • @AjayBrahmakshatriya ho can i use scanf to achieve the same purpose as is done by array[0] = "james" – Sahil Kumar Jul 10 '17 at 17:05

1 Answers1

0

array[1] and array[1] are unitialised pointers. You are therefore writing the data to an invalid or undefined location. The pointers need to reference allocated memory.

Both code fragments are incorrect, but the thing about an unitialised pointer, it may contain a legal address, or an invalid address, but in any event the address is not defined.

char array[2][64];
scanf("%63s",array[0]);
scanf("%63s",array[1]);
Clifford
  • 88,407
  • 13
  • 85
  • 165