簡體   English   中英

UNIX上的C程序轉儲核心

[英]c program dumping core on unix

我是C語言的新手。

下面的程序在Windows上運行良好,但是當我在solaris上用gcc編譯時,這是轉儲核心

#include<stdio.h>
#include<stdlib.h>

void main()
{
char *name;
name="James Bond";
int i=0;
sprintf(name,"%s/%d",name,i);
printf("String is %s",name);
}

請建議

您不能像這樣修改字符串文字,根據標准它是未定義的。 您正在嘗試用其他數據( sprintf )覆蓋該字符串文字。

許多實現會將它們放置在只讀內存中,從而導致核心轉儲-它們是很好的實現。 壞的情況將繼續,好像一切正​​常,通常不是這樣。

您可以嘗試以下方法:

#include <stdio.h>

int main (void) {
    char *name;
    char name2[100];  // make sure plenty of space.
    name = "James Bond";
    int i = 0;
    sprintf (name2, "%s/%d", name, i);
    printf ("String is %s\n", name2);
    return 0;
}

大多數此類問題的代碼如下:

name = "Bob";
*name = 'J';   // to try and make "Job"

但它只是為未定義寫入使用字符串文字sprintf為好。


基於注釋,您希望能夠合並路徑和文件規范。 您可以像執行以下操作:

char *path = "/tmp/";
char *file = "xyz.txt"
char fullpath = malloc (strlen (path) + strlen (file) + 1);
if (fullpath == NULL)
    // error and exit condition
strcpy (fullpath, path);
strcat (fullpath, file);
// use fullpath for your nefarious purposes :-)
free (fullpath);

這是一種方法,還有其他方法。

char *name;
name="James Bond";   // name is pointing into read-only memory
int i=0;
sprintf(name,"%s/%d",name,i); // trying to write to read-only memory
printf("String is %s",name);

而是使用緩沖區

char name[32] = "James Bond";
...

在C中定義和初始化常量字符串的正確方法是

char name[]="James Bond";

您的代碼可能是這樣的:

#include<stdio.h>
#include<stdlib.h>
void main()
{
    char name[] = "James Bond";
    int i = 0;

        printf("String is %s/%d", name,i);

}

您的“名稱”字符串長度不足,無法容納使用sprintf向其打印的字符集-您需要為所有字符分配足夠的緩沖區。

您需要使用malloc / calloc或將其定義為固定長度的變量來為name指針分配內存: char name[50] (例如)

在Linux和具有GNU Libc的系統上,您還可以使用asprintf進行編碼

char* str = NULL; // pointer should be initialized to NULL
asprintf (&str, "someformat %d", 20);

使用GTK時,您也可以調用g_strdup_printf

您應該了解C語言中數組與指針之間的區別和相似之處。許多書籍或講座都對此進行了詳細說明。

問候。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM