473,808 Members | 2,797 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

0a appending w/strcpy

I have a linked list where each node holds a couple numbers a char
and a const char array. I use strcpy to take an char array
argument passed to my insert function to copy the string into
the new node.

To some of these entries 0a(line feed?) is being appended.
I've looked through the faq and googled but haven't found much
info that applies.

The code follows this post(in a bit I'll split it into multiple
files for use in a larger project).

Regards,
Newbie Grant

<-------------------------------

#include <stdio.h>
#include <stdlib.h>
struct motNode {
struct motNode * next;
unsigned int opCode;
char type;
unsigned int numArgs;
char opName[];
};
typedef struct motNode motList;
motList *mot_head, * mot_cur;
int mot_insert(unsi gned int opCode, char type, unsigned int numArgs,
const char * opName){
mot_cur = (motList *)malloc(sizeof (motList));
mot_cur->opCode = opCode;
mot_cur->type = type;
mot_cur->numArgs= numArgs;
strcpy(mot_cur->opName, opName);
mot_cur->next = mot_head;
mot_head = mot_cur;
}

mot_dump(){
while(mot_cur){
printf("%s\n",m ot_cur->opName);
mot_cur = mot_cur->next;
}
}

generate_mot(){
mot_head = NULL;
mot_insert(0,'r ',0,"hlt");
mot_insert(1,'r ',3,"add");
mot_insert(2,'r ',3,"sub");
mot_insert(3,'r ',3,"mul");
mot_insert(4,'r ',3,"div");
mot_insert(5,'r ',3,"mod");
mot_insert(6,'r ',2,"move");
mot_insert(7,'r ',3,"and");
mot_insert(8,'r ',3,"or");
mot_insert(9,'r ',3,"xor");
mot_insert(10,' r',2,"com");
mot_insert(11,' r',3,"sll");
mot_insert(12,' r',3,"srl");
mot_insert(13,' r',3,"sra");
mot_insert(14,' r',3,"jr");
mot_insert(15,' r',1,"rdr");
mot_insert(16,' r',1,"prr");
mot_insert(17,' r',1,"prh");

/* I format */
mot_insert(18,' i',2,"li");
mot_insert(19,' i',3,"addi");
mot_insert(20,' i',3,"subi");
mot_insert(21,' i',3,"muli");
mot_insert(22,' i',3,"divi");
mot_insert(23,' i',3,"modi");
mot_insert(24,' i',3,"lwb");
mot_insert(25,' i',3,"swb");

/* J format */
mot_insert(26,' j',2,"lwa");
mot_insert(27,' i',2,"swa");
mot_insert(28,' i',1,"j");
mot_insert(29,' i',1,"jal");
mot_insert(30,' i',1,"jeq");
mot_insert(31,' i',1,"jne");
mot_insert(32,' i',1,"jlt");
mot_insert(33,' i',1,"jle");
mot_insert(34,' i',1,"jgt");
mot_insert(35,' i',1,"jge");
}

main(int argv, char * argc[]){
FILE * infle;
int
eofl,
fcount = 2;

if(argv < 3){
fprintf(stderr, "Too few arguments\n");
fprintf(stderr, "\tusage:\t p2 <flag> <input files:minimum of one>\n");
exit(1);
}
generate_mot();
mot_dump();
do{
printf("infle :: %s\n",argc[fcount]);
if((infle = fopen(argc[fcount],"r")) == NULL){
fprintf(stderr, "Unable to open data file %s\n",argc[fcount]);
}
else{
//do work
fclose(infle);
}
fcount++;
} while(fcount < argv);

}

--------------------------------->
Nov 14 '05 #1
17 1844
"Grant Austin" <ga*****@foo.fo o.bar.net> wrote in message
news:pa******** *************** *****@foo.foo.b ar.net...
I have a linked list where each node holds a couple numbers a char
and a const char array. I use strcpy to take an char array
argument passed to my insert function to copy the string into
the new node.

To some of these entries 0a(line feed?) is being appended.
I've looked through the faq and googled but haven't found much
info that applies.

The code follows this post(in a bit I'll split it into multiple
files for use in a larger project).

Regards,
Newbie Grant

<-------------------------------

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

struct motNode {
struct motNode * next;
unsigned int opCode;
char type;
unsigned int numArgs;
char opName[];
};

typedef struct motNode motList;
The two declarations above could be combined into one, did you know it?
Mind you, I wouldn't do it, typedefing structures is rarely a good idea.

But the most important point and probably a source of your problem is
the declaration of your opName field. You really need to give it a size.
I am surprised it even compiles.
motList *mot_head, * mot_cur;
Globals are another thing that is almost never a good idea.
int mot_insert(unsi gned int opCode, char type, unsigned int numArgs,
const char * opName){
mot_cur = (motList *)malloc(sizeof (motList));
Two things here. First, do not cast the return value from maloc(). It is
not necessary in C and may hide potential problems, when you forget to
include stdlib.h. Second, you need to check the malloc()'s return value.
mot_cur->opCode = opCode;
mot_cur->type = type;
mot_cur->numArgs= numArgs;
strcpy(mot_cur->opName, opName);
Here is your problem. You copy something to opName, but how much room
you have in opName? A typical example of UB (Undefined Behaviour).
mot_cur->next = mot_head;
mot_head = mot_cur;
}
Your function is declared as returning int, so where is it? Better yet,
let it return a pointer to your new created node and get rid of a global
variable.
mot_dump(){
while(mot_cur){
printf("%s\n",m ot_cur->opName);
mot_cur = mot_cur->next;
}
} Another function that fails to return int, even though it is declared
as such (although implicitly). Also, it relies on mot_cur being set up
before calling. Why don't you set it up in the function? Then you could
get rid of another global variable. It would need a pointer to a head
as a parameter.
generate_mot(){
mot_head = NULL;
mot_insert(0,'r ',0,"hlt");
mot_insert(1,'r ',3,"add"); .... mot_insert(34,' i',1,"jgt");
mot_insert(35,' i',1,"jge");
}
Yet again, where's your return?
main(int argv, char * argc[]){
FILE * infle;
int
eofl,
fcount = 2;

if(argv < 3){
fprintf(stderr, "Too few arguments\n");
fprintf(stderr, "\tusage:\t p2 <flag> <input files:minimum of one>\n");
exit(1);
1 is not a portable value to be returned from main() or used in exit().
Use EXIT_SUCCESS or EXIT_FAILURE, both defined in stdlib.h, which you
already include.
}
generate_mot();
mot_dump();
do{
printf("infle :: %s\n",argc[fcount]);
if((infle = fopen(argc[fcount],"r")) == NULL){
fprintf(stderr, "Unable to open data file %s\n",argc[fcount]);
}
else{
//do work
fclose(infle);
}
fcount++;
} while(fcount < argv);
return EXIT_SUCCESS;
}

--------------------------------->

Nov 14 '05 #2
Thanks for all of the comments, things are becoming clearer.
I'll be digesting for a while. (=

I'm creating the list as global because I will need access to it
in functions in other files. I thought that there might be quite
a bit of overhead passing the list to those functions. Now I realize
I can just pass a pointer to the head of the list.

Regards,
-G
Nov 14 '05 #3


Grant Austin wrote:
I have a linked list where each node holds a couple numbers a char
and a const char array. I use strcpy to take an char array
argument passed to my insert function to copy the string into
the new node.

To some of these entries 0a(line feed?) is being appended.
I've looked through the faq and googled but haven't found much
info that applies.


.............co de snipped.......
There are many errors.
The major error is that you did not allocate storage space for the
struct that will store the string. Here is your code modified to
show one way you might want to define function mot_insert.

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

struct motNode
{
struct motNode * next;
unsigned int opCode;
char type;
unsigned int numArgs;
char *opName;
};
typedef struct motNode mot_List;

int mot_insert(mot_ List **mot_head,unsi gned int opCode, char type,
unsigned int numArgs, const char * opName);
void mot_dump(mot_Li st *mot_cur);
void generate_mot(mo t_List **mot_cur);
void mot_free(mot_Li st **mot_cur);

int main(void)
{
mot_List *mot_head = NULL;

generate_mot(&m ot_head);
mot_dump(mot_he ad);
mot_free(&mot_h ead);
return 0;
}

int mot_insert(mot_ List **mot_head,unsi gned int opCode, char type,
unsigned int numArgs, const char * opName)
{
mot_List *mot_cur = malloc(sizeof *mot_cur);

if(mot_cur == NULL) return 0;
if((mot_cur->opName = malloc(strlen(o pName)+1)) == NULL)
{
free(mot_cur);
return 0;
}
mot_cur->opCode = opCode;
mot_cur->type = type;
mot_cur->numArgs= numArgs;
strcpy(mot_cur->opName, opName);
mot_cur->next = *mot_head;
*mot_head = mot_cur;
return 1;
}

void mot_dump(mot_Li st *mot_cur)
{
while(mot_cur)
{
printf("%s\n",m ot_cur->opName);
mot_cur = mot_cur->next;
}
}

void generate_mot(mo t_List **mot_cur)
{
mot_insert(mot_ cur,0,'r',0,"hl t");
mot_insert(mot_ cur,1,'r',3,"ad d");
mot_insert(mot_ cur,2,'r',3,"su b");
mot_insert(mot_ cur,3,'r',3,"mu l");
mot_insert(mot_ cur,4,'r',3,"di v");
mot_insert(mot_ cur,5,'r',3,"mo d");
mot_insert(mot_ cur,6,'r',2,"mo ve");
mot_insert(mot_ cur,7,'r',3,"an d");
mot_insert(mot_ cur,8,'r',3,"or ");
mot_insert(mot_ cur,9,'r',3,"xo r");
mot_insert(mot_ cur,10,'r',2,"c om");
mot_insert(mot_ cur,11,'r',3,"s ll");
mot_insert(mot_ cur,12,'r',3,"s rl");
mot_insert(mot_ cur,13,'r',3,"s ra");
mot_insert(mot_ cur,14,'r',3,"j r");
mot_insert(mot_ cur,15,'r',1,"r dr");
mot_insert(mot_ cur,16,'r',1,"p rr");
mot_insert(mot_ cur,17,'r',1,"p rh");

/* I format */
mot_insert(mot_ cur,18,'i',2,"l i");
mot_insert(mot_ cur,19,'i',3,"a ddi");
mot_insert(mot_ cur,20,'i',3,"s ubi");
mot_insert(mot_ cur,21,'i',3,"m uli");
mot_insert(mot_ cur,22,'i',3,"d ivi");
mot_insert(mot_ cur,23,'i',3,"m odi");
mot_insert(mot_ cur,24,'i',3,"l wb");
mot_insert(mot_ cur,25,'i',3,"s wb");

/* J format */
mot_insert(mot_ cur,26,'j',2,"l wa");
mot_insert(mot_ cur,27,'i',2,"s wa");
mot_insert(mot_ cur,28,'i',1,"j ");
mot_insert(mot_ cur,29,'i',1,"j al");
mot_insert(mot_ cur,30,'i',1,"j eq");
mot_insert(mot_ cur,31,'i',1,"j ne");
mot_insert(mot_ cur,32,'i',1,"j lt");
mot_insert(mot_ cur,33,'i',1,"j le");
mot_insert(mot_ cur,34,'i',1,"j gt");
mot_insert(mot_ cur,35,'i',1,"j ge");
}

void mot_free(mot_Li st **mot_cur)
{
mot_List *tmp;

for( ; *mot_cur; *mot_cur = tmp)
{
tmp = (*mot_cur)->next;
free(*mot_cur);
}
return;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4
On Sat, 28 Feb 2004 12:17:34 -0500, Al Bowers wrote:
....text snipped...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct motNode
{
struct motNode * next;
unsigned int opCode;
char type;
unsigned int numArgs;
char *opName;
};
typedef struct motNode mot_List;

int mot_insert(mot_ List **mot_head,unsi gned int opCode, char type,
unsigned int numArgs, const char * opName);
void mot_dump(mot_Li st *mot_cur);
void generate_mot(mo t_List **mot_cur);
void mot_free(mot_Li st **mot_cur);

int main(void)
{
mot_List *mot_head = NULL;

generate_mot(&m ot_head);
mot_dump(mot_he ad);
mot_free(&mot_h ead);
return 0;
}

....code snipped...

Thanks for the suggestions & code. With all of the help
I'm getting here I might have a chance at not sucking in a couple
years.

I'm not sure I understand what is meant by mot_List **mot_cur
and mot_List *mot_cur. Is **mot_cur a reference to a pointer? Is *mot_cur
the value of the pointer?
Thanks,
Grant

Nov 14 '05 #5
>"Grant Austin" <ga*****@foo.fo o.bar.net> wrote in message
news:pa******* *************** ******@foo.foo. bar.net...
struct motNode {
struct motNode * next;
unsigned int opCode;
char type;
unsigned int numArgs;
char opName[];
};

typedef struct motNode motList;
In article <news:40******* *@mk-nntp-2.news.uk.tisca li.com>
Peter Pichler <pi*****@pobox. sk> writes:
The two declarations above could be combined into one, did you know it?
Mind you, I wouldn't do it, typedefing structures is rarely a good idea.
Also, rather than combining them, if one really likes typedefs, one
should write the typedef first:

typedef struct X stX;

because that allows the alias to occur inside the structure:

struct X {
stX *next; /* linked list of struct X */
...
};

The "combo thing", "typedef struct X { ... } stX;", gives you the
worst of both worlds: not only do you have an not-strictly-necessary
alias just to avoid typing the letters "ruct" :-) (in this case);
you cannot even use it inside the braces.
But the most important point and probably a source of your problem is
the declaration of your opName field. You really need to give it a size.
I am surprised it even compiles.


This kind of declaration is a new C99-only "feature" called a
"flexible array member". The effect is as if you declared the
array with size zero (if C had zero-sized objects, which it does
not even if it should [in my opinion]).
mot_cur = (motList *)malloc(sizeof (motList));


Two things here. First, do not cast the return value from maloc(). It is
not necessary in C and may hide potential problems, when you forget to
include stdlib.h. Second, you need to check the malloc()'s return value.


And if one is going to use the new C99-only feature, one must also add
space for the name:
mot_cur->opCode = opCode;
mot_cur->type = type;
mot_cur->numArgs= numArgs;
strcpy(mot_cur->opName, opName);


Here is your problem. You copy something to opName, but how much room
you have in opName? A typical example of UB (Undefined Behaviour).


Indeed. Hence:

mot_cur = malloc(sizeof *mot_cur) + strlen(opName) + 1;

Note that a string whose strlen() is L requires L+1 bytes to store,
because one byte is needed for the '\0' marking the end.

As the FAQ notes, most (though not necessarily all) C89 compilers
allow you to use undefined behavior usefully by making the array
have size 1:

struct S {
...
char name[1];
};
...
struct S *p = malloc(sizeof *p + strlen(name));
...
strcpy(p->name, name);

In this case, the "+1" for the terminating '\0' is handled by giving
the array a size of 1. Unfortunately, the undefined behavior aspect
means you cannot count on this working on other systems, even if
it works on yours -- so you have to decide whether any savings you
find by using this so-called "struct hack" is worth the loss of
portability. (I have used it myself, in code that is not meant to
be strictly portable, in the data structures that describe potential
and ongoing DMA operations in devices. The NetBSD / FreeBSD
device-DMA model is based on this same idea, and in fact, the names
in a bus_dmamap_t are the ones I suggested. DMA areas are described
by a sequence of <ds_addr,ds_len > pairs, stored in an array allocated
via the "struct hack".)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #6
On Sat, 28 Feb 2004 16:39:43 +0000, Peter Pichler wrote:
.....snip
#include <stdio.h>
#include <stdlib.h>

struct motNode {
struct motNode * next;
unsigned int opCode;
char type;
unsigned int numArgs;
char opName[];
};

typedef struct motNode motList;


The two declarations above could be combined into one, did you know it?


....snip...

Not that I'm going to do it but do you mean you can do something
like this?:

typedef struct motNode{
struct motNode * next;
unsigned int opCode;
..
..
} motList;
-G
Nov 14 '05 #7
"Grant Austin" <ga*****@foo.fo o.bar.net> wrote in message
news:pa******** *************** *****@foo.foo.b ar.net...
On Sat, 28 Feb 2004 16:39:43 +0000, Peter Pichler wrote:
....snip
#include <stdio.h>
#include <stdlib.h>

struct motNode {
struct motNode * next;
unsigned int opCode;
char type;
unsigned int numArgs;
char opName[];
};

typedef struct motNode motList;


The two declarations above could be combined into one, did you know it?


...snip...

Not that I'm going to do it but do you mean you can do something
like this?:

typedef struct motNode{
struct motNode * next;
unsigned int opCode;
..
..
} motList;


Yes, that's what I meant. But read Chris Torek's post first, before dashing
off to do it ;-)

Peter
Nov 14 '05 #8
"Chris Torek" <no****@torek.n et> wrote in message
"Grant Austin" <ga*****@foo.fo o.bar.net> wrote in message

Peter Pichler <pi*****@pobox. sk> writes:

....
mot_cur = (motList *)malloc(sizeof (motList)); .... mot_cur->opCode = opCode;
mot_cur->type = type;
mot_cur->numArgs= numArgs;
strcpy(mot_cur->opName, opName);


Here is your problem. You copy something to opName, but how much room
you have in opName? A typical example of UB (Undefined Behaviour).


Indeed. Hence:

mot_cur = malloc(sizeof *mot_cur) + strlen(opName) + 1;


ITYM moving this----------------------^ here----------------^ ;-)

Thanks for the other comments.

Peter
Nov 14 '05 #9
On Sat, 28 Feb 2004 17:57:35 +0000, Chris Torek wrote:
Indeed. Hence:

mot_cur = malloc(sizeof *mot_cur) + strlen(opName) + 1;


I'm doing something like this now, thanks to Mr. Bowers:
motList *mot_cur = malloc(sizeof *mot_cur);
mot_cur->opName = malloc(strlen(o pName)+1));

This looks like the same thing just longer.

(I do check what malloc returns in the actual code)

Thanks for the comments. My mind is trying to cave in on itself.
I'm going to go decompress before I take a crack at the hash table
where each node contains a list of integers.

If anyone was wondering and hadn't figured it out -- I'm writing
a one pass assembler.
Regards,
Grant
Nov 14 '05 #10

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

Similar topics

7
3352
by: Paul Sheer | last post by:
I need to automatically search and replace all fixed size buffer strcpy's with strncpy's (or better yet, strlcpy's) as a security and stability audit. The code base is large and it is not feasable to manually perform these changes. I would like perhaps a C++ parser that can automatically detect use of a strcpy to a buffer of fixed size. For instance, struct x { char member;
3
1934
by: MLH | last post by:
I have a query, qryAppend30DayOld260ies that attempts to append records to tblCorrespondence. When run, it can result in any of the following: appending no records, appending 1 record or appending many records. Two of the target fields in tblCorrespondence receiving values in the append operation are and . For any given VehicleJobID value, I want only ONE record in correspondence table to have an value of "01". This query blindly appends...
9
7785
by: Ape Ricket | last post by:
Hi. During my program's set-up phase where it reads in the arguments it was invoked with, I programmed this: if (strcmp(argv,"-G") ==0) { geom_scaling = ON; if (i < argc-1) strcpy(geom_string,argv); }
81
7364
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
4
1673
by: John A Grandy | last post by:
could someone explain the following to me : Appending the literal type character I to a literal forces it to the Integer data type. Appending the identifier type character % to any identifier forces it to Integer.
302
18627
by: Lee | last post by:
Hi Whenever I use the gets() function, the gnu c compiler gives a warning that it is dangerous to use gets(). Is this due to the possibility of array overflow? Is it correct that the program flow can be altered by giving some specific calculated inputs to gets()? How could anyone do so once the executable binary have been generated? I have heard many of the security problems and other bugs are due to array overflows.
55
7106
by: Jake Thompson | last post by:
I need to copy a value into a char * field. I am currently doing this strcpy(cm8link.type,"13"); but I get an error of error C2664: 'strcpy' : cannot convert parameter 1 from 'const char' to 'char *'
9
2656
by: jim | last post by:
i want to make a c file that i can 'scanf ' students scores of 2 classes and their names , and i want it to get the sum of the 2 scores and make them in order .at last 'printf' /*am sorry,my english is not very good ,so u may have some difficulties in understanding my meaning ,but u can see the follow c file . thank u !*/
38
2735
by: edu.mvk | last post by:
Hi I am using strcpy() in my code for copying a string to another string. i am using static char arrays. for the first time it is exected correctly but the second time the control reaches then the SEGMENTATION FAULT is occuring. Please tell me what are all the cases this problem may occur if we use strcpy().
0
9600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10373
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5547
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5685
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4331
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3859
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.