Ich bin mir nicht sicher, was ich falsch mache. Ich versuche, hostname
mit pid
zu verknüpfen, um id
zu erstellen.Verkettung von String und int ergibt Segmentierungsfehler in C
char *generate_id(void) {
int ret;
char id[1048];
char hostname[1024];
pid_t pid = getpid();
//hostname[1023] = '\0';
if ((ret = gethostname(hostname,1024) < 0)) {
perror("gethostname");
exit(EXIT_FAILURE);
}
sprintf(id, "%s%d", pid);
printf("hostname is %s\n", hostname);
printf("The process id is %d\n", pid);
printf("The unique id is %s", id);
return id;
}
EDIT:
aktualisiert Code nach ein paar Antworten zu lesen:
char *generate_id(void) {
int ret;
char hostname[1024];
pid_t pid = getpid();
//hostname[1023] = '\0';
if ((ret = gethostname(hostname,1024) < 0)) {
perror("gethostname");
exit(EXIT_FAILURE);
}
int size = snprintf(NULL, 0, "%s%d", hostname, pid);
char * id = malloc(size + 1);
printf("hostname is %s\n", hostname);
printf("The process id is %d\n", pid);
printf("The unique id is %s\n", id);
return id;
}
EDIT:
Arbeitscode:
char *generate_id(void) {
int ret;
char hostname[1024];
pid_t pid = getpid();
//hostname[1023] = '\0';
if ((ret = gethostname(hostname,1024) < 0)) {
perror("gethostname");
exit(EXIT_FAILURE);
}
int size = snprintf(NULL, 0, "%s%d", hostname, pid);
char * id = malloc(size + 1);
sprintf(id, "%s%d", hostname, pid);
printf("hostname is %s\n", hostname);
printf("The process id is %d\n", pid);
printf("The unique id is %s\n", id);
return id;
}
sprintf '% s% d', und dann nur' pid' bereitstellen? Sie haben zwei Formatierungszeichen, also müssen Sie zwei Werte angeben. –
Warum haben Sie '% s% d' in sprintf sollte das nicht nur'% d' sein – JackVanier
Sie sollten 'pid_t pid' bei der Lieferung als' int' darstellen Streit. 'sprintf (id,"% d ", (int) pid);' –