473,385 Members | 1,396 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

struct and string pointers

Hi,

I'm new to c and I have no idea what I'm doing wrong. Running the
attached program gives me the output:

t1: 1234567890123456STRANGE
t2: STRANGE

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

Thanks for any help! / 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;
}

Nov 14 '05 #1
5 7376
Sorry, a glitch. The text was:
When i run this i get,

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

but only when the first string is 16 or 36 (...?) chars long.
Whats wrong with it? I'm running gcc 3.3 on mac os x panther (-ansi
-pedantic -Wall).

/ Paul
Nov 14 '05 #2
Paul wrote:

I'm new to c and I have no idea what I'm doing wrong. Running the
attached program gives me the output:
.... snip ...
------------------------------------------------------------------
Name: ss.c
ss.c Type: Plain Text (text/plain)
Encoding: 7bit


And also to newsgroups, evidently. Do not use attachments. Cut
and paste complete compilable programs into your message.
Attachments are potentially evil, and many ISPs automatically
delete them in non-binary newsgroups.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #3
pa***@mondo.mine.nu (Paul Diaconescu) wrote in message news:<8c**************************@posting.google. com>...
Sorry, a glitch. The text was:
When i run this i get,

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

but only when the first string is 16 or 36 (...?) chars long.
Whats wrong with it? I'm running gcc 3.3 on mac os x panther (-ansi
-pedantic -Wall).

/ Paul


It executed properly on my system or it was just lucky :)
As far as I can tell in your add_to_t function you have a local pointer
(struct target *t) which doesn't point to a valid memory location.

Gerald R. Generoso
Nov 14 '05 #4
On Sun, 18 Jan 2004 00:56:53 +0100, in comp.lang.c , Paul
<pa***@mondo.mine.nu> wrote:
Hi,

I'm new to c and I have no idea what I'm doing wrong. Running the
attached program gives me the output:

t1: 1234567890123456STRANGE
t2: STRANGE
.....but only for strlen(s1) = multiples of the default alignment on
your computer...... this is a hint !
temp = malloc(strlen(s) * sizeof(char));


Think about how long strlen(s) is, and whether it includes the
terminating null on the string. Then think about how your compiler
places objects in memory, and whether it leaves space between them...
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #5
On Sun, 18 Jan 2004 00:56:53 +0100, Paul <pa***@mondo.mine.nu> wrote:
Hi,

I'm new to c and I have no idea what I'm doing wrong. Running the
attached program gives me the output:

t1: 1234567890123456STRANGE
t2: STRANGE

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

Thanks for any help! / 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));
This does not allocate enough space. strlen returns the number of
characters in the string NOT including the terminating '\0'. However,
if you want to copy the string, you must have enough space to include
the '\0'.

sizeof(char) is guaranteed to always be 1 so you don't need it in the
argument expression.

strcpy(temp, s);
You have now invoked undefined behavior by running beyond the end of
the area temp points to.

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);
Apparently, when strlen(s) is a multiple of 16, the area allocated in
this second call to add_to_t immediately follows the area allocated in
the first call, overlaying the '\0' which is just outside the area
allocated. This is a really unlucky manifestation of undefined
behavior because it led you to believe your code was correct.

printf("t1: %s\nt2: %s\n", t.t1, t.t2);
In the situation described, t1 does not point to a string (because the
'\0' is flat out missing or not part of the allocated memory).

return 0;
Your program never frees the memory allocated by add_to_t.
This is called a memory leak and is bad programming practice (tm).
}


<<Remove the del for email>>
Nov 14 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Casper | last post by:
How would one go about summing up the memmory custom tree structures occupies in memmory? Example: struct node { struct node *parent; unsigned int nChildCount; string folder; //string class...
5
by: uny ternally | last post by:
I was experimenting in Visual C++ and ran into the following problem. I have the struct listed below. I also have a function that passes a variable of the struct type by reference and set the...
20
by: fix | last post by:
Hi all, I feel unclear about what my code is doing, although it works but I am not sure if there is any possible bug, please help me to verify it. This is a trie node (just similar to tree nodes)...
67
by: S.Tobias | last post by:
I would like to check if I understand the following excerpt correctly: 6.2.5#26 (Types): All pointers to structure types shall have the same representation and alignment requirements as each...
7
by: Mo | last post by:
I am having problem with marshaling struct in C#. //the original C++ struct typedef struct _tagHHP_DECODE_MSG { DWORD dwStructSize; // Size of decode structure. TCHAR ...
32
by: Weiguang Shi | last post by:
Hi, Is there a tool that, given a struct definition, generates a function that parses binary data of this struct and a command that can be used to construct binary data according to...
1
by: stromhau | last post by:
Hi, I have made a few classes in c++. They somehow cooperate doing some 3d stuff. Basically it is a moving camera acting as a flight, i have placed a lot of objects around the scene together with...
14
by: Frank | last post by:
Hello everyone, I am having trouble overloading the < operator for an assignment. I use a struct that contains information and I would like to sort this structure using STL sort with my own...
4
by: pallav | last post by:
hello, i'm sorry if this is a bit off topic but perhaps some of you here have experience with c++ with lex/yacc and can help me. i wrote a small lexer/parser using lex/yacc. i'm using c++ as...
4
by: Sheldon | last post by:
Hi, I have a unique case where I need an array of structs that grows and within this array is another struct that grows in some cases. I'm having trouble allocating memory. Since I have never...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.