473,699 Members | 2,525 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Looking for malloc() help

SP
I am learning C and have a question re: malloc().

I wrote simple program which assigns a value to a structure and then
prints it as follow:

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

struct item {
char name[20];
int quantity;
};

int main (int argc, char *argv[])
{
struct item *stuff;

//allocate memory for structure
stuff = malloc(3 * sizeof(struct item));

strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
strcpy(stuff[2].name, "banana");
stuff[2].quantity = 2;

printf("%s %d\n", stuff[1].name, st.quantity);
printf("%s %d\n", stuff[2].name, st.quantity);

free(stuff);
return 0;
}

I then change the structure declaration in order to dynamically
allocate memory
for the char array:
struct item {
char *name;
int quantity;
};

The program compiles with no errors, but it crashes with the following
error:

line 3: 2485 Segmentation fault

Thanks for your help

Aug 3 '06
19 1964
Herbert Rosenau wrote:
On Thu, 3 Aug 2006 03:02:20 UTC, "xiaohuamao "
<ca************ **@gmail.comwro te:
I don't know what is the problem. The following code works in my
machine.
struct item {
char* name;
int quantity;
};

int main ()
{
struct item *stuff;

//allocate memory for structure
stuff = (struct item *)malloc(3 * sizeof(struct item));

Never ever cast the result from malloc() except you like to go into
the lands of undefined behavior and you dont like to get diagnostics
from your compiler when you've forget to include stdlib.h.
Or if you want C++ compatibility, for whatever reason. (It may not make
sense for most C code, but one of the times it does make sense is if
it's an inline function in a header file that's kept after
installation.)
Never ever cast something - excet you knows exactly what you're
doing. casting the result of a function returning void* is playing
with the health of y<or app because you does NOT know what you does.
When you would know what you does you would never cast that.
You can quite legitimately cast a void * return value if you want to
store it as an (u)intptr_t value.

I wouldn't have commented if you hadn't so specifically said "never".

Aug 4 '06 #11
SP wrote:
I am learning C and have a question re: malloc().

I wrote simple program which assigns a value to a structure and then
prints it as follow:

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

struct item {
char name[20];
int quantity;
};

int main (int argc, char *argv[])
{
struct item *stuff;

//allocate memory for structure
stuff = malloc(3 * sizeof(struct item));

strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
strcpy(stuff[2].name, "banana");
stuff[2].quantity = 2;

printf("%s %d\n", stuff[1].name, st.quantity);
printf("%s %d\n", stuff[2].name, st.quantity);

free(stuff);
return 0;
}

I then change the structure declaration in order to dynamically
allocate memory
for the char array:
struct item {
char *name;
int quantity;
};

The program compiles with no errors, but it crashes with the following
error:

line 3: 2485 Segmentation fault

Thanks for your help
But you didn't allocate the memory. You'll need something like..

stuff[1].name = malloc(20);

...before

strcpy(stuff[1].name, "apple");

...and then you must free stuff[1].name (and stuff[2].name) before
freeing stuff.
--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Aug 5 '06 #12
On Fri, 4 Aug 2006 06:27:22 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
Herbert Rosenau wrote:

Never ever cast the result from malloc() except you like to go into
the lands of undefined behavior and you dont like to get diagnostics
from your compiler when you've forget to include stdlib.h.

Or if you want C++ compatibility, for whatever reason. (It may not make
sense for most C code, but one of the times it does make sense is if
it's an inline function in a header file that's kept after
installation.)
No. In C++ you would use simply operator new.
Never ever cast something - excet you knows exactly what you're
doing. casting the result of a function returning void* is playing
with the health of y<or app because you does NOT know what you does.
When you would know what you does you would never cast that.

You can quite legitimately cast a void * return value if you want to
store it as an (u)intptr_t value.
You can burn your home, no question. Bit is it a good idea to do so?
You can kill your wife too. Casting is insidious and casing void* to
anything else says nothing but you knows not how to handle pointers to
void.
I wouldn't have commented if you hadn't so specifically said "never".
It is simply: never ever cast the result of a function returning a
pointer to void. You'll end up in the lands of undifined behavior..

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Aug 6 '06 #13
Herbert Rosenau wrote:
On Fri, 4 Aug 2006 06:27:22 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
Herbert Rosenau wrote:
>
Never ever cast the result from malloc() except you like to go into
the lands of undefined behavior and you dont like to get diagnostics
from your compiler when you've forget to include stdlib.h.
Or if you want C++ compatibility, for whatever reason. (It may not make
sense for most C code, but one of the times it does make sense is if
it's an inline function in a header file that's kept after
installation.)

No. In C++ you would use simply operator new.
new is not an option when writing header files that work both for C and
for C++ code.
Never ever cast something - excet you knows exactly what you're
doing. casting the result of a function returning void* is playing
with the health of y<or app because you does NOT know what you does.
When you would know what you does you would never cast that.
You can quite legitimately cast a void * return value if you want to
store it as an (u)intptr_t value.

You can burn your home, no question. Bit is it a good idea to do so?
You can kill your wife too. Casting is insidious and casing void* to
anything else says nothing but you knows not how to handle pointers to
void.
How would you use (u)intptr_t, then? (If you say you wouldn't at all,
keep in mind that it's a type defined in standard C(99).)
I wouldn't have commented if you hadn't so specifically said "never".

It is simply: never ever cast the result of a function returning a
pointer to void. You'll end up in the lands of undifined behavior..
That's clearly untrue, and depending on your intent quite possibly a
lie. There's no undefined behaviour in casting the result of malloc().
It's usually poor style, and it can cover up warnings when the
behaviour would be just as undefined without a cast, but that's all.

Aug 6 '06 #14
On Sun, 6 Aug 2006 14:47:01 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
Herbert Rosenau wrote:
On Fri, 4 Aug 2006 06:27:22 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
Herbert Rosenau wrote:

Never ever cast the result from malloc() except you like to go into
the lands of undefined behavior and you dont like to get diagnostics
from your compiler when you've forget to include stdlib.h.
>
Or if you want C++ compatibility, for whatever reason. (It may not make
sense for most C code, but one of the times it does make sense is if
it's an inline function in a header file that's kept after
installation.)
No. In C++ you would use simply operator new.

new is not an option when writing header files that work both for C and
for C++ code.
But you says that it is good to write programs for both C anf FORTRAN
or C++ and Cobol?
You can't write a single program that uses two highly different
languages. When you needs to write failsave programs instead of
hacking blind around you have to use either C or C++. Mixing up
languages inside the same program ends always up with holes of any
kind.
Never ever cast something - excet you knows exactly what you're
doing. casting the result of a function returning void* is playing
with the health of y<or app because you does NOT know what you does.
When you would know what you does you would never cast that.
>
You can quite legitimately cast a void * return value if you want to
store it as an (u)intptr_t value.
You can burn your home, no question. Bit is it a good idea to do so?
You can kill your wife too. Casting is insidious and casing void* to
anything else says nothing but you knows not how to handle pointers to
void.

How would you use (u)intptr_t, then? (If you say you wouldn't at all,
keep in mind that it's a type defined in standard C(99).)
I would use it as it is defined. Conversion between all kinds of data
pointer to/from pointer to void is done already witrhout cast. When
you does not know what you does you should avoid cats anyway.
I wouldn't have commented if you hadn't so specifically said "never".
It is simply: never ever cast the result of a function returning a
pointer to void. You'll end up in the lands of undifined behavior..

That's clearly untrue, and depending on your intent quite possibly a
lie. There's no undefined behaviour in casting the result of malloc().
It's usually poor style, and it can cover up warnings when the
behaviour would be just as undefined without a cast, but that's all.
You must learn C before you can use the language, so start learning C.
Until you have learned C you are absolutely unable to something about
the language. You've proven now that you knows nothing about C.

Will you guarantee that in each and any environment a function
returning a pointer uses always the same location as a function
returning int, even as the standard since more than 15 years says the
contrary.

You knows nothing about C but tells nonsense. There are more traps you
falls in as you can dream of when you does not understund what C is -
and you have not even basic knowlede about C yet.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!

Aug 6 '06 #15
"Herbert Rosenau" <os****@pc-rosenau.dewrite s:
On Sun, 6 Aug 2006 14:47:01 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
>Herbert Rosenau wrote:
On Fri, 4 Aug 2006 06:27:22 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:

Herbert Rosenau wrote:


Never ever cast the result from malloc() except you like to go into
the lands of undefined behavior and you dont like to get diagnostics
from your compiler when you've forget to include stdlib.h.

Or if you want C++ compatibility, for whatever reason. (It may not make
sense for most C code, but one of the times it does make sense is if
it's an inline function in a header file that's kept after
installation.)

No. In C++ you would use simply operator new.

new is not an option when writing header files that work both for C and
for C++ code.

But you says that it is good to write programs for both C anf FORTRAN
or C++ and Cobol?
No, he didn't say that.
You can't write a single program that uses two highly different
languages. When you needs to write failsave programs instead of
hacking blind around you have to use either C or C++. Mixing up
languages inside the same program ends always up with holes of any
kind.
C and C++ are not "highly different"; C is nearly (but not exactly) a
subset of C++, and it's possible to write reasonable code within the
intersection of the two languages.

It rarely makes sense to do so. 99% of the time, it makes more sense
to write in pure C, or to write in pure C++, or to use C++'s 'extern
"C"' mechanism if you need to use both. But it's also possible to
write library code that's intended to be used by either C or C++
client code. P.J. Plauger does this, for example.

--
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.
Aug 6 '06 #16
Keith Thompson said:

<snip>
But it's also possible to
write library code that's intended to be used by either C or C++
client code. P.J. Plauger does this, for example.
And the reason his name is always given as an example is that he's almost
the only guy in the universe with a good reason to do this.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Aug 6 '06 #17
Herbert Rosenau wrote:
On Sun, 6 Aug 2006 14:47:01 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
Never ever cast something - excet you knows exactly what you're
doing. casting the result of a function returning void* is playing
with the health of y<or app because you does NOT know what you does.
When you would know what you does you would never cast that.

You can quite legitimately cast a void * return value if you want to
store it as an (u)intptr_t value.
>
You can burn your home, no question. Bit is it a good idea to do so?
You can kill your wife too. Casting is insidious and casing void* to
anything else says nothing but you knows not how to handle pointers to
void.
How would you use (u)intptr_t, then? (If you say you wouldn't at all,
keep in mind that it's a type defined in standard C(99).)

I would use it as it is defined. Conversion between all kinds of data
pointer to/from pointer to void is done already witrhout cast. When
you does not know what you does you should avoid cats anyway.
It is impossible in standard C to store a pointer value in an
(u)intptr_t object without a cast. Using a cast in this case, according
to you, shows you don't know how to handle pointers. So I ask again,
how would you use (u)intptr_t?
I wouldn't have commented if you hadn't so specifically said "never".
>
It is simply: never ever cast the result of a function returning a
pointer to void. You'll end up in the lands of undifined behavior..
That's clearly untrue, and depending on your intent quite possibly a
lie. There's no undefined behaviour in casting the result of malloc().
It's usually poor style, and it can cover up warnings when the
behaviour would be just as undefined without a cast, but that's all.

[Insult snipped]
Will you guarantee that in each and any environment a function
returning a pointer uses always the same location as a function
returning int, even as the standard since more than 15 years says the
contrary.
[Insult snipped]
No, that's clearly untrue, no disagreement there, but where is the
undefined behaviour in this program?

#include <stdlib.h>
int main(void) {
free( (char *) malloc(1) );
}

What I said, if you would re-read my message, is that the cast itself
does not invoke undefined behaviour. What does invoke undefined
behaviour is giving an improper declaration of malloc(), but malloc()
is properly declared here. A cast can happen to hide a diagnostic
caused by an improper declaration, but the behaviour is not defined
with or without it.

Aug 6 '06 #18
Herbert Rosenau wrote:
On Sun, 6 Aug 2006 14:47:01 UTC, "Harald van D�k" <tr*****@gmail. com>
wrote:

>>Herbert Rosenau wrote:
>>>On Fri, 4 Aug 2006 06:27:22 UTC, "Harald van D�k" <tr*****@gmail. com>
wrote:
Herbert Rosenau wrote:

>Never ever cast the result from malloc() except you like to go into
>the lands of undefined behavior and you dont like to get diagnostics
>from your compiler when you've forget to include stdlib.h.

Or if you want C++ compatibility, for whatever reason. (It may not make
sense for most C code, but one of the times it does make sense is if
it's an inline function in a header file that's kept after
installatio n.)

No. In C++ you would use simply operator new.

new is not an option when writing header files that work both for C and
for C++ code.


But you says that it is good to write programs for both C anf FORTRAN
or C++ and Cobol?
Where did "programs' come from? The discussion was about headers.
>
You can't write a single program that uses two highly different
languages. When you needs to write failsave programs instead of
hacking blind around you have to use either C or C++. Mixing up
languages inside the same program ends always up with holes of any
kind.
But they do (often) share headers.

--
Ian Collins.
Aug 6 '06 #19

Herbert Rosenau wrote:
On Sun, 6 Aug 2006 14:47:01 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
Herbert Rosenau wrote:
On Fri, 4 Aug 2006 06:27:22 UTC, "Harald van Dk" <tr*****@gmail. com>
wrote:
Herbert Rosenau wrote:
Never ever cast something - excet you knows exactly what you're
doing. casting the result of a function returning void* is playing
with the health of y<or app because you does NOT know what you does.
When you would know what you does you would never cast that.

You can quite legitimately cast a void * return value if you want to
store it as an (u)intptr_t value.
>
You can burn your home, no question. Bit is it a good idea to do so?
You can kill your wife too. Casting is insidious and casing void* to
anything else says nothing but you knows not how to handle pointers to
void.
How would you use (u)intptr_t, then? (If you say you wouldn't at all,
keep in mind that it's a type defined in standard C(99).)

I would use it as it is defined. Conversion between all kinds of data
pointer to/from pointer to void is done already witrhout cast. When
you does not know what you does you should avoid cats anyway.
Please show us your code to store a void * in a uintptr_t without a
cast.
...

You must learn C before you can use the language, so start learning C.
Until you have learned C you are absolutely unable to something about
the language. You've proven now that you knows nothing about C.
Hmmm ...
Will you guarantee that in each and any environment a function
returning a pointer uses always the same location as a function
returning int, even as the standard since more than 15 years says the
contrary.
How's that relevant?
You knows nothing about C but tells nonsense. There are more traps you
falls in as you can dream of when you does not understund what C is -
and you have not even basic knowlede about C yet.
You need to be on more solid ground than you are to make comments like
these without looking foolish.

Aug 7 '06 #20

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

Similar topics

16
2287
by: Fronsac | last post by:
Hi, I've been asked in a job interview how to make C code look like C++ code, and honestly I didn't know what to answer because I have never really done a lot of C. Now, I've been searching around the web about web sites that talk about this subject, but I've had no luck. Can anyone point me to some web site about this subject? Thanks a lot!
5
1904
by: mikegw | last post by:
Hello all. I am currently using an implementation of sysV shared memory. The entire shared memory is allocated is one continuous block of which I get the pointer to the head, everything should be done as offsets from this. At the moment I have two data structures, a head to a linked list which in it contains the pointer to the first element in the linked list( this is redundant as far as I can work out) and the list itself. The data...
1
2416
by: Dawn Minnis | last post by:
Hey guys - this code when called with parameters: driver.o n n 12 12 12 12 12 12 2.6 3.2 is kicking back a segmentation fault. I've read the rest of the postings but am still confused. Can someone take a look and tell me how to fix it - please dont be like the guy I spoke to today and tell me that I am not allocating the memory correctly and then walk off. Please, if possible provide me with
7
2912
by: Novice | last post by:
When Main calls a function, which has a couple of malloc() statements, and their corresponding free() statements, why did it crash? How should I fix this problem? TIA
20
1903
by: dimka | last post by:
Hello Here is my situation: I have a char buf; that is used as a buffer for a log output. Normally, I do: rc = snprintf( buf, sizeof(buf), some_format, some_args ); This makes the formatting my output and then I flush the buffer. In 90% of cases this works well, exept the cases when the format or the
318
12958
by: jacob navia | last post by:
Rcently I posted code in this group, to help a user that asked to know how he could find out the size of a block allocated with malloc. As always when I post something, the same group of people started to try to find possible errors, a harmless passtime they seem to enjoy. One of their remarks was that I used "int" instead of "size_t" for the input of my allocator function.
1
1883
by: Kevin | last post by:
Hi all, I clearly have an issue with some pointers, structures, and memory allocation. Its probably pritty basic, but I'm a little stuck. Any help would be greatly appreciated. I'd like to instantiate an arbitrary number of arrays of arbitrary size in function_a, copy the pointers, store the data, and free any unused memory. My basic structure is as follows:
34
13381
by: niranjan.singh | last post by:
This is regarding to test an SDK memory stuff. In what situation malloc gets fail. any comment/reply pls.... regards
16
5092
by: graham.keellings | last post by:
hi, I'm looking for an open source memory pool. It's for use on an embedded system, if that makes any difference. Something with garbage collection/defragmentation would be nice. It should have the ability to allocate different size chunks of memory not just a single size. It should error check for double free, etc. And it should be usable by a mixture of C and C++ subsystems. If I get that, I'm happy. Thank you very much.
0
8689
marktang
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...
0
8618
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
9178
Oralloy
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...
1
8916
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,...
0
8885
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...
0
5875
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();...
0
4631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3058
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
2348
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.