Hello all. I am writing a command shell, but am having trouble with
memory allocations. I am trying to tokenise a string into a **char
array for execvp (the unix launch-this-program function), but I get
segmentation faults when I run it.
Here is the code that I use to parse the string, which fails:
char buf[] = "abcde fghij klmno"; /* sample string */
int arg = 0, pos = 0, i, in_string = 0;
char **args = NULL;
args = malloc(1 + sizeof(char *));
if (args == NULL) { printf("malloc failed"); exit(1); }
for (i = 0; buf[i]; i++) {
char c = buf[i];
/* Space -> move on to the next argument */
if (c == ' ' && pos != 0 && in_string == 0) {
arg++; /* next argument */
args[arg] = (char *) realloc(args, pos + 1);
args[arg][0] = '\0';
pos = 0;
args = (char **) realloc(args, arg * sizeof(char *));
/* add another line */
if (args == NULL) { printf("realloc failed (1)");
exit(1); }
continue;
}
/* Quotes -> toggle being in a string */
if (c == '"') {
in_string = !in_string;
continue;
}
/* backslash -> skip a character */
if (c == '\\') c = buf[++i];
/* Anything else -> add to the args list */
args[arg] = realloc(args, (pos) * sizeof(char) + 1); /* resize
to fit the new character */
if (args[arg] == NULL) { printf("realloc failed (2)"); exit(1);
}
args[arg][pos] = c;
args[arg][pos+1] = '\0'; /* so it is a null-terminated string
*/
pos++;
}
The length of **args should be increasing to fit whatever I try to put
in it, but it is not.
It parses the first letter fine, but segfaults on the second. Sometimes
it likes the second letter too, but segfaults on the third. I ran it
through the gnu debugger, and it always faults on the line
"args[arg][pos+1] = '\0';", so I am thinking that I am not allocating
enough, or allocating in the wrong place.
What is wrong? 3 1557
benjamin sago wrote: Hello all. I am writing a command shell, but am having trouble with memory allocations.
Yes, you are. I think you need to re-read the relevant section of your
text book.
I am trying to tokenise a string into a **char array for execvp (the unix launch-this-program function), but I get segmentation faults when I run it.
Here is the code that I use to parse the string, which fails:
Is this your complete code, copied and pasted from your source file not
re-typed? If so it has major problems.
#include <stdlib.h> /* Required for malloc and friends */
char buf[] = "abcde fghij klmno"; /* sample string */ int arg = 0, pos = 0, i, in_string = 0;
char **args = NULL; args = malloc(1 + sizeof(char *));
Why initialise args then immediately overwrite the initial value?
char **args = malloc(1 + sizeof(char *));
Although I still don't think this is what you want. Why the 1+? What are
you trying to achieve?
The more normal form is:
char **args = malloc(N + sizeof *args);
where N is the number of elements you want space for.
if (args == NULL) { printf("malloc failed"); exit(1); }
1 is not a portable value for exit. Use exit(EXIT_FAILU RE) instead.
for (i = 0; buf[i]; i++) { char c = buf[i];
/* Space -> move on to the next argument */ if (c == ' ' && pos != 0 && in_string == 0) { arg++; /* next argument */ args[arg] = (char *) realloc(args, pos + 1);
What are you trying to do here? I really think this is nothing like what
you are thinking. malloc & realloc know nothing about 2D arrays, but I'm
guessing you think they do. In any case, this is definitely completely
wrong. I suggest you read the comp.lang.c FAQ starting with sections 6 &
7, but read the rest as well. http://www.eskimo.com/~scs/c-faq.com/aryptr/index.html http://www.eskimo.com/~scs/c-faq.com/malloc/index.html
Also, don't cast the return value of realloc. It isn't required.
Then you need to check the return value as well.
args[arg-1] = malloc(space required for string, not
forgetting null termination);
The -1 is because you have already incremented arg.
args[arg][0] = '\0'; pos = 0; args = (char **) realloc(args, arg * sizeof(char *)); /* add another line */
A bit better, but more likely
args = realloc(args, arg * sizeof *args);
<snip>
I've not checked the rest because it is already so far off the mark by
here that I didn't see the point. I've also not checked the logic of
your argument passing.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro: http://clc-wiki.net/wiki/Intro_to_clc
Flash Gordon opined: benjamin sago wrote: Hello all. I am writing a command shell, but am having trouble with memory allocations. Yes, you are. I think you need to re-read the relevant section of your text book.
> I am trying to tokenise a string into a **char array for execvp (the unix launch-this-program function), but I get segmentation faults when I run it.
Here is the code that I use to parse the string, which fails:
Is this your complete code, copied and pasted from your source file not re-typed? If so it has major problems.
#include <stdlib.h> /* Required for malloc and friends */
char buf[] = "abcde fghij klmno"; /* sample string */ int arg = 0, pos = 0, i, in_string = 0;
char **args = NULL; args = malloc(1 + sizeof(char *));
Why initialise args then immediately overwrite the initial value? char **args = malloc(1 + sizeof(char *)); Although I still don't think this is what you want. Why the 1+? What are you trying to achieve?
The more normal form is: char **args = malloc(N + sizeof *args); where N is the number of elements you want space for.
You mean:
char **args = malloc(N * sizeof *args);
or I have misread both the OP or your reply (I read it as "space for N
pointers to `char` is required"). if (args == NULL) { printf("malloc failed"); exit(1); }
1 is not a portable value for exit. Use exit(EXIT_FAILU RE) instead.
for (i = 0; buf[i]; i++) { char c = buf[i];
/* Space -> move on to the next argument */ if (c == ' ' && pos != 0 && in_string == 0) { arg++; /* next argument */ args[arg] = (char *) realloc(args, pos + 1);
What are you trying to do here? I really think this is nothing like what you are thinking. malloc & realloc know nothing about 2D arrays, but I'm guessing you think they do. In any case, this is definitely completely wrong. I suggest you read the comp.lang.c FAQ starting with sections 6 & 7, but read the rest as well. http://www.eskimo.com/~scs/c-faq.com/aryptr/index.html http://www.eskimo.com/~scs/c-faq.com/malloc/index.html
Also, don't cast the return value of realloc. It isn't required.
Then you need to check the return value as well.
args[arg-1] = malloc(space required for string, not forgetting null termination);
The -1 is because you have already incremented arg.
args[arg][0] = '\0'; pos = 0; args = (char **) realloc(args, arg * sizeof(char *)); /* add another line */
A bit better, but more likely args = realloc(args, arg * sizeof *args);
<snip>
I've not checked the rest because it is already so far off the mark by here that I didn't see the point. I've also not checked the logic of your argument passing.
--
"It's God. No, not Richard Stallman, or Linus Torvalds, but God."
(By Matt Welsh)
<http://clc-wiki.net/wiki/Introduction_to _comp.lang.c>
Vladimir S. Oka wrote: Flash Gordon opined:
benjamin sago wrote: Hello all. I am writing a command shell, but am having trouble with memory allocations. Yes, you are. I think you need to re-read the relevant section of your text book.
> I am trying to tokenise a string into a **char array for execvp (the unix launch-this-program function), but I get segmentation faults when I run it.
Here is the code that I use to parse the string, which fails: Is this your complete code, copied and pasted from your source file not re-typed? If so it has major problems.
#include <stdlib.h> /* Required for malloc and friends */
char buf[] = "abcde fghij klmno"; /* sample string */ int arg = 0, pos = 0, i, in_string = 0;
char **args = NULL; args = malloc(1 + sizeof(char *)); Why initialise args then immediately overwrite the initial value? char **args = malloc(1 + sizeof(char *)); Although I still don't think this is what you want. Why the 1+? What are you trying to achieve?
The more normal form is: char **args = malloc(N + sizeof *args); where N is the number of elements you want space for.
You mean:
char **args = malloc(N * sizeof *args);
or I have misread both the OP or your reply (I read it as "space for N pointers to `char` is required").
You are correct, I did mean to multiply. I blame this notebooks keyboard ;-)
<snip>
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro: http://clc-wiki.net/wiki/Intro_to_clc This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Sean Dettrick |
last post by:
Hi,
Can anyone please tell me if the following is possible, and
if so, what is the correct syntax?
I'd like to resize a vector (and access other vector member functions)
via a pointer to that vector, e.g:
vector<int> x(10);
vector<int>* p = &x;
*p.resize( 5 );
cout << *p << endl;
|
by: Gregory L. Hansen |
last post by:
I can't seem to make a queue of objects, using the STL queue. I'm trying
to make a little event manager, and I just want someplace to store events.
The method definitions for EventManager have been commented away to
nothing during debugging, but the headers look like
class Event
{
private:
Object* recipient;
int eventID;
|
by: tuko |
last post by:
Hello kind people.
Can someone explain please the following code?
/* Create Storage Space For The Texture */
AUX_RGBImageRec *TextureImage; /* Line 1*/
/* Set The Pointer To NULL */
memset(TextureImage,0,sizeof(void *)*1); /* Line 2*/
According to my knowledge in the first line
|
by: Thomas G. Marshall |
last post by:
Arthur J. O'Dwyer <ajo@nospam.andrew.cmu.edu> coughed up the following:
> On Thu, 1 Jul 2004, Thomas G. Marshall wrote:
>>
>> Aside: I've looked repeatedly in google and for some reason cannot
>> find what is considered to be the latest ansi/iso C spec. I cannot
>> even find C99 in its final draft. Where in ansi.org or the like do
>> I find it?
>
> The official C99 specification is copyright ISO and distributed by
> various national...
|
by: Eric |
last post by:
hi,
I want to convert a C# class into COM, so that I can use the class in C++.
The codes compile and link well. But when I run the program, I got a
exception.
Any comment is welcome. Thanks in advance.
Eric
| |
by: Ruan |
last post by:
My confusion comes from the following piece of code:
memo = {1:1, 2:1}
def fib_memo(n):
global memo
if not n in memo:
memo = fib_memo(n-1) + fib_memo(n-2)
return memo
I used to think that the time complexity for this code is O(n) due to its
|
by: Neil |
last post by:
Hello all!
I wrote program with a array of pointers, and I suspect they are
pointing at each other in the Do ...While loop.
Something is messed up with the increment variable word. A program
clip of what I'm talking about.
#include <stdio.h>
#include <string.h>
|
by: aj |
last post by:
Can someone explain why this example works:
bool SomeFunction(const char * ipIpAddress, int &opOct1, int &opOct2,
int &opOct3, int
&opOct4)
{
int b1, b2, b3, b4;
unsigned char c;
|
by: dli07 |
last post by:
Hello,
I'm trying to convert a piece of code that creates a dynamic vertical resizing bar in a table from internet explorer to firefox. It's based on a post from http://blogs.crankygoblin.com/blogs/geoff.appleby/pages/50712.aspx. I've also read the post on this topic by bggraphics, but he doesn't arrive at a final result. The main problem I am having is that the layerX and layerY event properties don't work. They're supposed to return the...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
| |
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...
| |