473,748 Members | 2,212 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 #1
19 1972
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));

stuff[1].name = (char *) malloc(sizeof(" apple"));
strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
stuff[2].name = (char *) malloc(sizeof(" banana"));
strcpy(stuff[2].name, "banana");
stuff[2].quantity = 2;
printf("%s %d\n", stuff[1].name, stuff[1].quantity);
printf("%s %d\n", stuff[2].name, stuff[2].quantity);
free(stuff);
return 0;
}

Aug 3 '06 #2
SP

xiaohuamao wrote:
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));

stuff[1].name = (char *) malloc(sizeof(" apple"));
strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
stuff[2].name = (char *) malloc(sizeof(" banana"));
strcpy(stuff[2].name, "banana");
stuff[2].quantity = 2;
printf("%s %d\n", stuff[1].name, stuff[1].quantity);
printf("%s %d\n", stuff[2].name, stuff[2].quantity);
free(stuff);
return 0;
}
Not sure it matters, my PC is as follows:

Linux Slackware 10.1
compiling program with "gcc -o test struct.c"

Is anyone else able to run this ?

Aug 3 '06 #3

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);
st has not been defined. You probably mean stuff[1].quantity
printf("%s %d\n", stuff[2].name, st.quantity);
stuff[2].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:
In the first case the struct contains memory (20 bytes) for storing the
names so the malloc() for the structs is sufficient. In the second
case the struct contains only a pointer, so you are copying "apple" to
whatever random address ends up in stuff[1].name. Undefined behaviour.[*]

You could either use malloc() to allocate space for storing the name
and assign the resulting pointer to stuff[1].name, or just do
stuff[1].name = "apple";
and not copy the string at all.

In this case just assigning the pointer would make more sense, but in a
real example either strategy might be appropriate.

-thomas

[*] Technically the undefined behaviour could be even worse than
copying to some random address, but that's bad enough.

Aug 3 '06 #4
"SP" <po******@susco m.netwrites:
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
So you've shown us the program that works, but not the one that
doesn't.

Ok, I'll assume that the change in the declaration of "struct item"
was the only change you made. The problem is that you haven't
allocated space for the strings "apple" and "banana". You need
to do something like:

stuff[1].name = malloc(some_num ber_of_bytes);
strcpy(stuff[1].name, "apple");

Some other notes:

If you don't use argc and argv, you can omit their declarations:
int main(void)

Always check the result of malloc(). If it fails for whatever reason,
you go on and try to access the memory anyway; this can Make Bad
Things Happen. Even if you just abort the program on failure, it's
better than ignoring it.

Your malloc() call is good, but there's a little trick that can make
it even better:

stuff = malloc(3 * sizeof *stuff);

This way, you don't have to repeat (and possibly get wrong) the type
of "stuff" in the malloc call, and if you change the type of stuff you
don't have to track down and change all the calls.

I presume you know you're using only the 2nd and 3rd of the 3 elements
you allocated for your array.

It's generally considered a good idea to avoid "//" comments when
posting to Usenet. News software often wraps long lines. If a "//"
comment is wrapped, it usually creates a syntax error; if a "/*
.... */" comment is wrapped, it's usually harmless. (And "//" comments
aren't supported in C90.)

--
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 3 '06 #5
SP said:
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));
Not bad, but better would be:

stuff = malloc(3 * sizeof *stuff); /* note the * in front of stuff */

because there's less to get wrong (you don't need to type the typename, so
you can't mess it up - not that you did, on this occasion), and it's more
robust in the face of subsequent changes to the pointer type.

But malloc can fail. In that eventuality, it will return NULL. You should
check for this before relying on the allocation.

For a "student exercise" such as this one, the following would be
sufficient:

if(stuff == NULL)
{
fputs("Insuffic ient memory to continue. Terminating program.\n",
stderr);
exit(EXIT_FAILU RE);
}
>
strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
You're not using stuff[0], then? Well, okay, it's your memory...
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;
}
That's fine, apart from what I've pointed out already.
>
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
Yes. Now that you've changed name from being an array to being a mere
pointer, you need to point it at some storage.

if(stuff != NULL)
{
int i;
for(i = 0; i < 3; i++)
{
stuff[i].name = malloc(20 * sizeof *stuff[i].name);
if(stuff[i].name == NULL)
{
fprintf(stderr, "Can't allocate space for name %d\n", i);
fprintf(stderr, "Terminatin g program.\n");
exit(EXIT_FAILU RE);
}
}

You will now be able to do your strcpy in safety (provided the string you
copy into it is 19 or fewer bytes long).

Once you've finished, and before you free(stuff), you should do this:

for(i = 0; i < 3; i++)
{
free(stuff[i].name);
}

Then you can free(stuff);

--
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 3 '06 #6
Thomas Lumley said:
>
SP wrote:
<snip>
>>
printf("%s %d\n", stuff[1].name, st.quantity);
st has not been defined. You probably mean stuff[1].quantity
> printf("%s %d\n", stuff[2].name, st.quantity);
Well spotted. I missed those completely.

--
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 3 '06 #7
SP

Richard Heathfield wrote:
Thomas Lumley said:

SP wrote:
<snip>
>
printf("%s %d\n", stuff[1].name, st.quantity);
st has not been defined. You probably mean stuff[1].quantity
printf("%s %d\n", stuff[2].name, st.quantity);

Well spotted. I missed those completely.

--
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)

Allocating memory for the char array was the part I didnt know how to
do,
now it works just fine.

Thanks to all.

Aug 3 '06 #8
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.

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.
stuff[1].name = (char *) malloc(sizeof(" apple"));
see above
strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
stuff[2].name = (char *) malloc(sizeof(" banana"));
see aboove
strcpy(stuff[2].name, "banana");
stuff[2].quantity = 2;
printf("%s %d\n", stuff[1].name, stuff[1].quantity);
printf("%s %d\n", stuff[2].name, stuff[2].quantity);
free(stuff);
Before you frees stuff you should free its members you've allocated
with malloc() to avoid memory leaks.

return 0;
}

Array starts with index 0, not 1. Why does you malloc 3 struct members
when you only needs 2? And why does you use the last but not the first
ones?

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Aug 4 '06 #9
On Thu, 3 Aug 2006 12:09:24 UTC, "SP" <po******@susco m.netwrote:
>
Richard Heathfield wrote:
Thomas Lumley said:
>
SP wrote:
<snip>
>>
> printf("%s %d\n", stuff[1].name, st.quantity);
st has not been defined. You probably mean stuff[1].quantity
> printf("%s %d\n", stuff[2].name, st.quantity);
Well spotted. I missed those completely.

--
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)


Allocating memory for the char array was the part I didnt know how to
do,
now it works just fine.
No, you've forgotten to include stdlib.h so even as it seems to work
you're sitting in the middle of the lands of undefined behavior.
Thanks to all.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Aug 4 '06 #10

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

Similar topics

16
2291
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
1905
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
2419
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
2916
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
1909
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
13009
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
1885
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
13398
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
5100
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
8979
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
9522
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...
0
9355
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...
1
9307
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
9225
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
6790
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
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2203
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.