[英]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.