C语言 执行期间的分段错误

iovurdzv  于 2023-03-22  发布在  其他
关注(0)|答案(4)|浏览(138)
#include<stdio.h>   
int main()  
{    
    char *arg[10],*c;  
    int count=0;  
    FILE *fp,*fq;  
    printf("Name of the file:");  
    scanf("%s",arg[1]);  
    fp=fopen(arg[1],"w");  
    printf("\t\t%s",arg[1]);  
    printf("Input the text into the file\n");  
    printf("Press Ctrl+d to the stop\n");  
    while((*c=getchar())!=EOF)  
    {  
            fwrite(c,sizeof(char),1,fp);  
            count++;  
    }  
    return 0;  
}
n9vozmp4

n9vozmp41#

更改此行

char *arg[10],*c;

char arg[1000],c;

这条线

scanf("%s",arg[1]);

scanf("%s",arg);

还有这条线

while((*c=getchar())!=EOF)

while((c=getchar())!=EOF)

说明:
char *c;不是一个字符,它是一个指向字符的 * 指针 *。它开始只是指向内存中的一个随机位,内存中通常会填充随机数据-无论最近写入了什么。
char c; * 是 * 一个字符。
同样的事情也适用于char *arg[10]。它是一个由十个指针组成的数组。它们指向随机内存,内存中充满了随机数据。
注意:我的修改不是最佳实践。如果有人要输入1000个字符或更长的文件名,你会写在arg缓冲区的末尾。根据你正在做的事情,这可能是一个安全错误。

wsxa1bj1

wsxa1bj12#

char *arg[10];

你定义了一个10个指向char的指针的数组,但你没有初始化它的元素. arg[0],arg[1],...,arg[9]都将有未定义的值。
然后,你试图在这些未定义的值中输入一个字符串。幸运的是,你得到了一个分段错误。如果你不幸运,你的程序could format your hard disk

svmlkihl

svmlkihl3#

char *arg[10] ;

arg是一个字符指针数组。你需要在输入之前使用malloc为它们分配内存位置-

scanf("%s",arg[1]); // arg[1] is not assigned to point to any memory location
                    // and is what causing the segmentation fault.

所以-

arg[1] = malloc( stringLengthExpectedToEnter + 1 ) ; // +1 for termination character

应该这样做,其余的数组元素太(或)简单地改变char*arg[10]char arg[10],并确保输入只输入9个字符。
我认为你混淆了指针普通变量

int *ptr;

ptr是一个可以保存整数变量地址的变量。内存被分配给ptr变量来保存整数地址。就是这样。ptr处于uninitialized状态,并且指向no where(或)可能指向垃圾。解引用未初始化指针的行为是未定义的,如果它给出segmentation-fault,你就足够幸运了。
现在,您需要使用malloc为其分配一个有效的内存位置。

ptr = malloc( sizeof(int) ) ; // Allocates number of bytes required to hold an
                              // integer and returns it's address.

因此,ptr现在指向的是从自由存储区获取的可以容纳整数的内存位置。从自由存储区获取的这些位置必须使用free释放,否则就会出现经典的内存泄漏问题。在声明时将指针初始化为NULL是一个很好的做法。

int *ptr = NULL ;

希望能有所帮助!

scanf("%d", ptr) ; // Notice that & is not required before ptr. Because ptr 
                   // content is address itself.

一个正常变量的故事是完全不同的。当声明-

int var ;

内存分配给var来保存一个整数。因此,您可以直接为其分配一个整数。

jchrr9hc

jchrr9hc4#

#include<stdio.h>   
int main()  
{    
   char arg[10],c;  
   int count=0;  
   FILE *fp;  
   printf("Name of the file:");  
   scanf("%s",arg);  
   fp=fopen(arg,"w");  
   printf("\t\t%s",arg);  
   printf("Input the text into the file\n");  
   printf("Press Ctrl+d to the stop\n");  
   while((c=getchar())!=EOF)  
   {  
        fwrite(&c,sizeof(char),1,fp);  
        count++;  
   }

   if(fp != NULL){
      fclose(fp);
      fp = NULL;
   }
   return 0;  
}

相关问题