简体   繁体   中英

c program dumping core on unix

I am a new learner of C language.

Below program run well on Windows but when i compile with gcc on solaris, this is dumping core

#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);
}

Please suggest

You cannot modify a string literal like that, it's undefined according to the standard. You're trying to overwrite that string literal with other data (the sprintf ).

Many implementations will place them in read-only memory, causing a core dump - they're the good ones. The bad ones will continue on as if everything's okay, which it usually isn't.

You could try the following:

#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;
}

Most questions of this type have code like:

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

but it's just as undefined to write to string literals using sprintf as well.


Based on comments, you want to be able tocombine a path and file spec. You could do this as something like:

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);

That's one way to do it, there are others.

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);

instead use a buffer

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

The correct way to define and initialize a constan string in C is

char name[]="James Bond";

Your code may be like this:

#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] (例如)

On Linux and systems with the GNU Libc, you can also code using asprintf

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

When using GTK, you could also call g_strdup_printf

You should understand the difference and similarities between arrays and pointers in C. Many many books or lectures explain that in detail.

Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM