简体   繁体   English

在shell上的此c程序中为什么会出现分段错误错误

[英]in this c program on shell why the segmentation fault error

why there is segmentation-fault error in the following code: 为什么在以下代码中出现细分错误

#include<stdio.h>

int main()
{
    char word[]="cs311cs312cs313";

    printf("%s %s %s %s",
           *word,
           *(word+2),
           *(word+4),
           *(word+8));

    return 0;
}

Is this error is due to compiler or there is some syntax error in my code ? 这个错误是由于编译器引起的还是我的代码中存在语法错误?

Modern compilers usually give warnings in such situations, for example: 现代编译器通常会在这种情况下发出警告,例如:

warning: format specifies type 'char *' but the argument has type 'char' [-Wformat] 警告:format指定类型为'char *',但是参数为类型'char'[-Wformat]

*(word+2) and others are pointer dereferencing , operation gets the actual value the pointer points to. *(word+2)等是指针解引用 ,操作获取指针指向的实际值。 This will give you chars 'c' , '3' and so. 这将给您字符'c''3'等。

Because printf has variable argument count - arguments after the format string will be put on stack raw, loosing types 由于printf具有可变的参数计数-格式字符串之后的参数将被放入堆栈中,从而失去类型

%s makes printf take a few bytes from stack and expect it to be a pointer to the string. %s使printf从堆栈中获取了几个字节,并期望它是指向字符串的指针。 Try printf("Char: %p, str:%p", 'c', "c"); 尝试printf("Char: %p, str:%p", 'c', "c"); to see what the passed address looks like. 查看传递的地址是什么样的。

Addresses like 0x63 in the very beginning of memory are valid, but your program is forbidden from accessing these, because the segment is not assigned to it, so you get the segmentation-fault / access violation 内存开头的地址类似0x63是有效的,但是您的程序被禁止访问这些地址,因为未将段分配给它,因此您会遇到segmentation-fault / access violation

So to fix the error - remove the unwanted dereferencing (the * s) 因此,要纠正错误-删除不需要的解引用( * s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM