分段错误(核心转储)

时间:2012-08-20 08:44:41

标签: c unix

我在以下代码中收到了分段错误(核心转储):

void Update_Log( )
{
        struct logData update;
        int file;

        char *writeBuffer=NULL;

        if((file=creat("/home/user/Desktop/DMS/DMS/filename.txt",O_RDONLY|O_WRONLY))==-1)
                perror("file not opened");
        update.clientName="user";
        update.filename="user";
        update.timestamp="some time";
        sprintf(writeBuffer,"%s %s %s",update.clientName,update.filename,update.timestamp);


        if((write(file,writeBuffer,sizeof(writeBuffer)))==-1)
                perror("write unsuccessful");
        close(file);
}

我的结构如下:

struct logData
{
        char *clientName;
        char *filename;
        char *timestamp;
};

有人可以提供帮助吗?

7 个答案:

答案 0 :(得分:2)

您正在尝试写入writeBuffer这是一个空指针,您应该将其声明为array(1),或者在堆(2)上为它分配一个内存。

  1. char writeBuffer[100];
  2. char *writeBuffer=malloc(100)
  3. 在这两种情况下,您都不应使用sprintf,而应使用snprintf来确保您的缓冲区没有溢出。

答案 1 :(得分:0)

创建'update'时,它只为字符串clientName,filename,timestamp的指针分配空间;它没有为字符串本身分配空间。快速破解就是执行类似update.clientName =(char *)malloc(sizeof(char)* len)的操作,其中len是您要分配的长度。那你应该真的检查那个电话的返回代码......

这与写缓冲区完全相同......您只需要确保为所有字符串分配空间。

答案 2 :(得分:0)

错误是这两行:

char *writeBuffer=NULL;

/* ... */

sprintf(writeBuffer, /* ... */);

在这里你写入NULL指针。

改为创建一个数组,例如

char writeBuffer[32];

答案 3 :(得分:0)

您需要为writeBuffer分配空间。

您可以使用malloc,或者如果您对数据大小有限制(例如,如果它将小于256字节),则将其声明为

char writeBuffer[256];

我还建议查找并使用snprintf而不是sprintf来确保数据不会结束。

答案 4 :(得分:0)

你的struct store只有指针,没有为实际数据分配内存。 要么你应该

struct logData
{
        char clientName[SOMEDEFINE1NUMBERHERE];
        char filename[SOMEDEFINE2NUMBERHERE];
        char timestamp[SOMEDEFINE3NUMBERHERE];
};

或者您分配内存(malloc

update.clientname =(char *)malloc(SOMEDEFINE1NUMBERHERE);    strncpy(update.clientname," user");

答案 5 :(得分:0)

由于Binyamin Sharet写道sprintf没有分配输出缓冲区。调用者必须提供足够长的输出缓冲区。这并不总是很简单。因此我建议你使用fopen而不是open。然后你可以这样编码:

void Update_Log( )  
{  
        struct logData update;  
        FILE *file = fopen("/home/user/Desktop/DMS/DMS/filename.txt", "w");  

        if(file==NULL) {  
                perror("file not opened");  
                return;
        }
        update.clientName="user";  
        update.filename="user";  
        update.timestamp="some time";  
        if(fprintf(file,"%s %s %s",update.clientName,update.filename,update.timestamp) < 0)  
                perror("write unsuccessful");  
        fclose(file);  

}

正如您所看到的,代码更短,并且没有潜在的缓冲区溢出。

答案 6 :(得分:-1)

崩溃了,因为writeBufferNULL

您需要使用malloc为writeBuffer分配内存 - 使用strlen(例如)来计算必要空间(不要忘记\0和{{1}中的空格}})。

或者,您可以自动分配一些固定大小的数组:

sprintf

此外,你不应该这样做:

char writeBuffer[ SOME_SIZE_BIG_ENOUGH ];

您有几种选择:

  • 使用strcpy
  • 使用 update.clientName="user"; update.filename="user"; update.timestamp="some time"; (POSSIX)
  • 制作指针strdup,而不只是const char*
相关问题