Segmentation Fault? Why?

Nitin

I don't know why this code shows Segmentation Fault.Below is the code

int main()
{   
    char *str;
    printf("\nEnter a string - \n");
    scanf("%s",str);
    printf("%s\n",str);
}

What can be the reasons for the segmentation fault? Also I would like to know why using gets()function is dangerous in Linux?

Sagar D

Firstly, you may need to know that you could have used char str[40] = {0}; (compile time memory allocation).

Since you have asked a question which queries about dynamic memory allocation, you should allocate memory to a pointer before trying to store anything. Beacuse the pointer may be pointing to any random locations (wild pointer) and hence you may try to access memory which is not meant for accessing, this results in a segfault.

int main()
{   
    char *str;
    str = malloc(sizeof(char) * 40); // allocate memory where str will be pointing,here i allocate 40 bytes
    printf("\nEnter a string - \n");
    scanf("%39s",str);
    printf("%s\n",str);
    free(str); //important to release the memory!
}

To answer your second question, gets() is dangerous on any platform because it may cause buffer overflow.

Consider a scenario where you try to fill a buffer beyond it’s capacity :

char *buff = malloc(sizeof(char)*10);
strcpy(buff, "This String Will Definitely Overflow the Buffer Because It Is Tooo Large");

As you can see that the strcpy() function will write the complete string in the ‘buff’ but as the size of ‘buff’ is less than the size of string so the data will get written past the right boundary of array ‘buff’. Now, depending on the compiler you are using, chances are high that this will get unnoticed during compilation and would not crash during execution. The simple reason being that memory belongs to program so any buffer overflow in this memory could get unnoticed.

So in these kind of scenarios, buffer over flow quietly corrupts the neighbouring memory and if the corrupted memory is being used by the program then it can cause unexpected results.

Workaround for safety :

char *buf=NULL; 
size_t siz= 30; 
ssize_t len = getline(&buf,&siz,stdin);

How is this a workaround?? Well, you should read about the getline() more.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Why is the segmentation Fault error occuring

분류에서Dev

A* Implementation in C, Segmentation fault

분류에서Dev

Segmentation Fault - GNU C

분류에서Dev

Segmentation fault in Assembly and string

분류에서Dev

Access Violation (Segmentation Fault)

분류에서Dev

Malloc to struct; segmentation fault

분류에서Dev

Segmentation Fault in hsearch

분류에서Dev

Strcpy Segmentation Fault C

분류에서Dev

Strange segmentation fault in code

분류에서Dev

Segmentation Fault on return statement

분류에서Dev

glGenBuffers crashing with Segmentation fault

분류에서Dev

Struct causing segmentation fault

분류에서Dev

Resetting Variable : Segmentation fault

분류에서Dev

Segmentation fault in sorting algorithm

분류에서Dev

I keep getting segmentation fault :11 errors and i can't figure out why... c++

분류에서Dev

Segmentation Fault While Sorting - Malloc

분류에서Dev

Fractional Knapsack Algorithm segmentation fault

분류에서Dev

Segmentation fault on reboot Ubuntu 12.04

분류에서Dev

C Segmentation fault using strtok

분류에서Dev

python Segmentation fault (core dumped)

분류에서Dev

Segmentation fault in sigaction signal handler

분류에서Dev

Segmentation fault on reverse string function

분류에서Dev

Segmentation fault with flex bison and yyparse

분류에서Dev

Depth first Minimax Segmentation Fault

분류에서Dev

while ... readdir causing segmentation fault

분류에서Dev

Graph adjacency matrix segmentation fault

분류에서Dev

Running bash does "segmentation fault core dumped"

분류에서Dev

Segmentation fault in recursive Binary Search Algorithm in C

분류에서Dev

Segmentation fault upon insertion into binary search tree