c程序在unix上转储核心

Dav*_*e A 1 c unix gcc

我是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);
}
Run Code Online (Sandbox Code Playgroud)

请建议

pax*_*blo 6

你不能像这样修改字符串文字,它根据标准是未定义的.您正试图用其他数据(the 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;
}
Run Code Online (Sandbox Code Playgroud)

此类型的大多数问题都有如下代码:

name = "Bob";
*name = 'J';   // to try and make "Job"
Run Code Online (Sandbox Code Playgroud)

但它只是为未定义写入使用字符串文字sprintf也是如此.


根据评论,您希望能够对路径和文件规范进行tocombine.你可以这样做:

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);
Run Code Online (Sandbox Code Playgroud)

这是一种方法,还有其他方法.