Hi,
I'm puzzled. Why does the following cause a seg fault? Notwithstanding
that I've already malloc() a certain space for "Hello".
I do understand that using a fixed length array will work very well.
But I wish to find out how can this be achieve using pointers.
Thank you.
Stan
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *Hello = NULL;
char *World = NULL;
Hello = malloc(100);
Hello = "hello";
World = "world";
strcat(Hello, World);
printf("%s\n",H ello);
return 0;
} 15 2012
Stanley S wrote: Hi,
I'm puzzled. Why does the following cause a seg fault? Notwithstanding that I've already malloc() a certain space for "Hello".
I do understand that using a fixed length array will work very well. But I wish to find out how can this be achieve using pointers.
Thank you.
Stan
#include <stdio.h> #include <stdlib.h>
#include <string.h> /* for the `str*' functions you call below */ int main(int argc, char *argv[]) {
char *Hello = NULL; char *World = NULL; Hello = malloc(100);
Here you (most likely -- you really *should* error check) allocate 100
chars of memory to the pointer `Hello'... Hello = "hello";
....which you promptly throw away (causing a memory leak) when you assign
the location of the literal string "hello" to it.
What you wanted was:
strcpy(Hello, "hello"); World = "world"; strcat(Hello, World); printf("%s\n",H ello);
return 0; }
HTH,
--ag
--
Artie Gold -- Austin, Texas http://goldsays.blogspot.com http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Stanley S wrote On 12/20/05 12:22,: Hi,
I'm puzzled. Why does the following cause a seg fault? Notwithstanding that I've already malloc() a certain space for "Hello".
I do understand that using a fixed length array will work very well. But I wish to find out how can this be achieve using pointers.
Thank you.
Stan
#include <stdio.h> #include <stdlib.h>
int main(int argc, char *argv[]) {
char *Hello = NULL; char *World = NULL; Hello = malloc(100);
Now `Hello' points to an anonymous chunk of memory
big enough to hold 100 characters. (Assuming malloc()
succeeded, which you should have checked.)
Hello = "hello";
Now `Hello' points to a completely different piece
of memory, namely, a six-character array initialized
with 'h','e','l','l' ,'o','\0'. It no longer points to
the memory obtained from malloc(). (As an aside, since
you no longer have any record of where that memory is,
you cannot find it even to free() it -- this is what's
known as a "memory leak.")
You probably wanted `strcpy(Hello, "hello");'.
World = "world"; strcat(Hello, World);
This attempts to append five more characters to the
six-character array, and there isn't room for them. The
effects are in general unpredictable; someday you will
come to appreciate how helpful a nice reproducible SIGSEGV
can be. You won't always be so lucky.
printf("%s\n",H ello);
return 0; }
Stanley S <St************ ***@gmail.com> wrote: Thanks a million guys.
It is proper Usenet etiquette to include the relevant portions of the text
you are replying to. To do this using Google groups, please follow the
instructions below, penned by Keith Thompson:
If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Stanley S a écrit : Hi,
I'm puzzled. Why does the following cause a seg fault? Notwithstanding that I've already malloc() a certain space for "Hello".
I do understand that using a fixed length array will work very well. But I wish to find out how can this be achieve using pointers.
Thank you.
Stan
#include <stdio.h> #include <stdlib.h>
int main(int argc, char *argv[]) {
char *Hello = NULL; char *World = NULL; Hello = malloc(100);
The value you have given to Hello is the address of an allocated block.
Hello = "hello";
Now, you are replacing this value by the address of a non mutable
string. Sounds nuts, isn't it ?
World = "world"; strcat(Hello, World);
Of course, the destination zone not being writable, the behaviour is
undefined. Anything can happen.
I suggest you consider a function to copy the string (say strcpy(), for
instance...)
printf("%s\n",H ello);
return 0; }
--
A+
Emmanuel Delahaye
Stanley S wrote: Hi,
I'm puzzled. Why does the following cause a seg fault? Notwithstanding that I've already malloc() a certain space for "Hello".
And promptly lost it ... #include <stdio.h> #include <stdlib.h>
int main(int argc, char *argv[]) {
char *Hello = NULL; char *World = NULL; Hello = malloc(100); Hello = "hello";
You just overwrote the pointer Hello to point to the string literal
"hello". Not only have you now lost the pointer to the space allocated
in the previous line, but the string literal "hello" is not guaranteed
to be writable.
World = "world"; strcat(Hello, World);
Even if the string literal "hello" were writable, it is only 6 chars
long, so you are now trying to write into the non-allocated space beyond
the probably unwritable string "hello".
printf("%s\n",H ello);
return 0; }
"Christophe r Benson-Manica" <at***@nospam.c yberspace.org> wrote in message
news:do******** **@chessie.cirr .com... Stanley S <St************ ***@gmail.com> wrote:
Thanks a million guys. It is proper Usenet etiquette to include the relevant portions of the text you are replying to. To do this using Google groups, please follow the instructions below, penned by Keith Thompson:
<snip> ... Flames welcome.
You asked for it... ;-)
<ot rant>
Now you're just being an idiot...
Problem was obviously solved and he was thanking those who answered.
The 'relevant portions of the text' he was replying to are no longer
relevant.
Stop being a dumbass.
Btw: Where in the usenet etiquette does it state that it is acceptable to
repeatedly post instructions to people who don't follow what you deam to
be acceptable usenet etiquette?
</ot rant>
"Mark B" <so***@localbar .com> writes:
[...] Btw: Where in the usenet etiquette does it state that it is acceptable to repeatedly post instructions to people who don't follow what you deam to be acceptable usenet etiquette?
We don't (usually) repeatedly post instructions to the same people.
We post instructions in response to people who probably haven't seen
them before. If you did a search for the authors of the parent
articles of all the followups containing Google instructions, I think
you'd find most of them are unique, and many of them get the message
and start to use Google properly.
See also <http://cfaj.freeshell. org/google/>.
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mark B wrote: "Christophe r Benson-Manica" <at***@nospam.c yberspace.org> wrote in message news:do******** **@chessie.cirr .com... Stanley S <St************ ***@gmail.com> wrote:
Thanks a million guys. It is proper Usenet etiquette to include the relevant portions of the text you are replying to. To do this using Google groups, please follow the instructions below, penned by Keith Thompson: <snip> ... Flames welcome.
You asked for it... ;-)
<ot rant> Now you're just being an idiot...
No, he is posting useful advice to those unfortunate enough to be using
Google for whatever reason.
Problem was obviously solved and he was thanking those who answered. The 'relevant portions of the text' he was replying to are no longer relevant.
Even then it is customary to at least leave a line or two in.
Stop being a dumbass.
There is no need to be insulting even if you disagree.
Btw: Where in the usenet etiquette does it state that it is acceptable to repeatedly post instructions to people who don't follow what you deam to be acceptable usenet etiquette?
It is not just what Christopher considers acceptable, it is normal
usenet etiquette. It is generally considered acceptable here to point
out normal posting conventions to those who are not aware of it, just as
it is considered acceptable to point people at the FAQ when the question
they ask is answered in the FAQ. You can tell it is generally considered
acceptable because a significant portion of the regulars do it and the
only regular poster I see complaining about it is a self acknowledged troll.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: stephenma7 |
last post by:
Hi, everybody. I am new here.
I have encountered these many problems for the last couple of days. I
have Linux Fedora Core 3(Gnu G++ 3.4.2), Linux Fedora Core 2 (Gnu G++
3.3.3), Red Hat 9 (Gnu G++ 3.2.2, this is dual processors).
I have the same set of programs that I wrote and when I ran on the
three machines, which have different amount of memories, processors'
speeds, and settings. I got three different seg faults at different...
|
by: Ian Stanley |
last post by:
Hi,
Having not done any C programming for a while I am trying to get back into
it by converting an old java assignment into C.
The problem is I am getting a segmentation fault at runtime which I am
having trouble fixing(program below)
The idea of the program is to convert input(integers) into words eg:
# 101
returns
#one hundred one
I have found the problem is with the strcat of the strings & literals --
|
by: Ian Stanley |
last post by:
Hi,
Continuing my strcat segmentation fault posting-
I have a problem which occurs when appending two sting literals using
strcat.
I have tried to fix it by writing my own function that does the strcat
(mystract). Program below.
However this appears not to have fixed the problem and I don't know why it
shouldn't ?
Any further help as to what else I am doing wrong will be appreciated
regards
|
by: Kevin C. |
last post by:
Never mind my last post about pointer subtraction, I traced the code and
found the offender to be strcat.
char call = "del ";
system(strcat(strcat(call, del->table_name), ".tab"));
After this line, trying to dereference del results in page faults or
garbage. This makes me wonder how strcat is implemented, in terms of what it
actually does with the arguments. Seems like it actually moves the pointer.
Anyone know?
|
by: Digital Puer |
last post by:
Hi, I'm coming over from Java to C++, so please bear with me.
In C++, is there a way for me to use exceptions to catch
segmentation faults (e.g. when I access a location off
the end of an array)?
Thanks.
| |
by: Paminu |
last post by:
I have a wierd problem.
In my main function I print "test" as the first thing. But if I run the call
to node_alloc AFTER the printf call I get a segmentation fault and test is
not printed!
#include <stdlib.h>
#include <stdio.h>
typedef struct _node_t {
|
by: lovecreatesbea... |
last post by:
This code snippet is an exercise on allocating two dimension array
dynamically. Though this one is trivial, is it a correct one?
Furthermore, when I tried to make these changes to the original
example:
for (i = 0; i < ROW + 2; ++i){ /*line 14*/
strcpy(array, "C! C!"); /*line 15*/
Apparently, the modified code wrote to the memory unit outside the
allocated array, but the program ran well and there was no Segmentation
|
by: mathieu.dutour |
last post by:
Dear all,
I am new to C and I have a problem with "segmentation fault" occurring
unexpectedly, i.e., not immediately after a programming error. I
presume
I allocated wrongly before, but I can't find the error, after
extensive search.
This is new situation to me as the vector class of C++ and the GAP
programming language (for algebraic computation) when a seg fault
|
by: Mahesh |
last post by:
Hi,
I am looking for efficient string cancatination c code. I did it using
ptr but my code i think is not efficient.
Please help.
Thanks a lot
|
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: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |