dimanche 3 juillet 2016

Influence of string length on uninitialized character pointer [duplicate]

This question already has an answer here:

The question is regarding "strcpy" using char pointer, which gives me segmentation fault. With a simple code below segmentation fault does not occur until no of characters in the string has reached 4 i.e "ZZZZ". why?

CASE 1:

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

int main()
{
    char *name;
    strcpy(name,"Z");
    printf("%sn",name);
    return 0;
}

output of this code is:

Z

CASE 2: When i use 2 characters in strcpy:

strcpy(name,"ZZ"); output of this code is:

ZZ

CASE 3: When i use 2 characters in strcpy:

strcpy(name,"ZZZ"); output of this code is:

ZZZ

CASE 4: When i use 2 characters in strcpy:

strcpy(name,"ZZZZ"); output of this code is:

ZZZZ Segmentation fault (core dumped)

Similar results are obtained not only with strcpy but also with gets/puts pair. There should be something related to the string length. I understand that the pointer has to be initialized properly. Here i just wanted to understand the reason for such a result because of its consistency. why after 4 characters ?

Aucun commentaire:

Enregistrer un commentaire