Struct with string pointers

P

Paul Diaconescu

Hi,

I'm new to c and I don't have any clue to what I'm doing wrong. This
program gives me the output:

t1: 1234567890123456STRANGE
t2: STRANGE ^
(this is strange)

But only when the first string is 16 or 32 (...) characters long. I'm
using gcc 3.3 from apple (build 1495) on mac os x panther (gcc -pedantic
-ansi -Wall).

/ Paul

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

struct target {
char *t1;
char *t2;
};


void add_to_t (struct target *t, const char *s) {
char *temp;
static int target = 0;

temp = malloc(strlen(s) * sizeof(char));

strcpy(temp, s);

if (target == 0)
t->t1 = temp;
else
t->t2 = temp;
++target;
}

int main (void) {
struct target t;
char *s1 = "1234567890123456";
char *s2 = "STRANGE";

add_to_t(&t, s1);
add_to_t(&t, s2);

printf("t1: %s\nt2: %s\n", t.t1, t.t2);

return 0;
}
 
H

Horst Kraemer

Hi,

I'm new to c and I don't have any clue to what I'm doing wrong. This
program gives me the output:

t1: 1234567890123456STRANGE
t2: STRANGE ^
(this is strange)

But only when the first string is 16 or 32 (...) characters long. I'm
using gcc 3.3 from apple (build 1495) on mac os x panther (gcc -pedantic
-ansi -Wall).

/ Paul

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

struct target {
char *t1;
char *t2;
};


void add_to_t (struct target *t, const char *s) {
char *temp;
static int target = 0;

temp = malloc(strlen(s) * sizeof(char));

temp = malloc(strlen(s)+1);

sizeof(char)==1 by definition.

A string is a sequence of characters terminated by the first null
character. The null character is part of the string.

strcpy will copy the string pointed to by s (including the terminating
null character). strlen gives the number of characters in the string
*preceding* the terminating null character.
 
J

Jarmo

Paul Diaconescu said:
Hi,

void add_to_t (struct target *t, const char *s) {
char *temp;
static int target = 0;

temp = malloc(strlen(s) * sizeof(char));

strcpy(temp, s);

if (target == 0)
t->t1 = temp;
else
t->t2 = temp;
++target;
}

You malloc one character too few. You need n+1 bytes to store a string of
length n because strings in C have an additional terminating zero byte.
Plus there is no need to use sizeof(char) as it's defined to equal 1.

So use: temp = malloc(strlen(s) + 1);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
474,135
Messages
2,570,783
Members
47,341
Latest member
hanifree

Latest Threads

Top