473,785 Members | 2,310 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc trouble

ncf
Hi all.

In another topic, I was informed that I had to dynamically allocate
memory instead of just trying to expand on a list. (I'm trying to learn
C, and have a strong background in PHP and Python) In light of that, I
have been trying to learn malloc, realloc, and free, but to no avail.

But for some reason, I'm getting segfaults right and left, and to be
honest, I am not having any luck at all really in finding out why it
isn't working. However, I have traced it and discovered that the
malloc() call is what is causing the problem. (traced by adding various
printf()s and then moving the malloc to it's own line)

It would be greatly appreciated if anyone can point out what the heck
I'm doing so wrong. Code snipplets are included at the end of this
message.

Thank you soo much in advance.

-Wes

/* at the "file" level */
#define BUFFLEN 100
char **messages;
int num_messages=0;
/* inside of main() */
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

Nov 15 '05 #1
27 1939
ncf wrote:
Hi all.

In another topic, I was informed that I had to dynamically allocate
memory instead of just trying to expand on a list. (I'm trying to learn
C, and have a strong background in PHP and Python) In light of that, I
have been trying to learn malloc, realloc, and free, but to no avail.

But for some reason, I'm getting segfaults right and left, and to be
honest, I am not having any luck at all really in finding out why it
isn't working. However, I have traced it and discovered that the
malloc() call is what is causing the problem. (traced by adding various
printf()s and then moving the malloc to it's own line)

It would be greatly appreciated if anyone can point out what the heck
I'm doing so wrong. Code snipplets are included at the end of this
message.

Thank you soo much in advance.

-Wes

/* at the "file" level */
#define BUFFLEN 100
char **messages;
[In the future post *real* *compilable* code. It makes things easier.]

What's the value of `messages' at his point?
int num_messages=0;
/* inside of main() */
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

Please see the FAQ, particularly the piece on `dynamic allocation of
multidimensiona l arrays'.

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com (new post 8/5)
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Nov 15 '05 #2
ncf
Alrighty, I just checked one comp.lang.c faq (located at
http://www.faqs.org/faqs/C-faq/faq/), and to be quite honest, the code
they're using is making little sense to me, but I will give it a shot.

And, even though it may or may not be necessary until I get the chance
to add the pointer allocation, the code is currently as follows:
/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
int num_messages=0;

int main(int argc, char **argv) {
char tmpmsg[][BUFFLEN] = {"a","b","c","d ","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tm pnum);

/* Do the copy loop */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocat ing space for %d.\n",x);
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_mess ages;x++) {
printf("%02d => %s\n",x,message s[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
free(messages[x]);
}

/* the end of the test...finally :P */
return 0;
}

Nov 15 '05 #3
ncf
Ok, wow, I think I get it now, but it would be grealy appreciated if
someone could look over my updated/modified code to make sure that it
does as it seems it should. Thank you for pointing out the obvious
(faq)--some days I deserve to be slapped :P

-Wes

/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
int num_messages=0;

int main(int argc, char **argv) {
char tmpmsg[][BUFFLEN] = {"a","b","c","d ","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tm pnum);

/* first, malloc 0*sizeof(char *) bytes for messages, as we have no
pointers yet */
messages = malloc(num_mess ages*sizeof(cha r *));

/* Do the copy loop */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocat ing space for %d.\n",x);
if ( (messages = realloc(message s, (num_messages+1 )*sizeof(char *)))
== NULL)
{
printf("Could not allocate space for one more pointer.\n");
return 1;
}
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_mess ages;x++) {
printf("%02d => %s\n",x,message s[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
free(messages[x]);
}
free(messages);

/* the end of the test...finally :P */
return 0;
}

Nov 15 '05 #4
>But for some reason, I'm getting segfaults right and left, and to be
honest, I am not having any luck at all really in finding out why it
isn't working. However, I have traced it and discovered that the
malloc() call is what is causing the problem. (traced by adding various
printf()s and then moving the malloc to it's own line)

It would be greatly appreciated if anyone can point out what the heck
I'm doing so wrong. Code snipplets are included at the end of this
message.

Thank you soo much in advance.

-Wes

/* at the "file" level */
#define BUFFLEN 100
char **messages;
int num_messages=0;
/* inside of main() */
You may not assign to messages[num_messages] until you
have assigned something to messages (and something other
than NULL), which you don't show here.
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))
==NULL)
{
printf("Could not allocate space.\n");
return 1;
}


Gordon L. Burditt
Nov 15 '05 #5
ncf wrote:
Ok, wow, I think I get it now, but it would be grealy appreciated if
someone could look over my updated/modified code to make sure that it
does as it seems it should. Thank you for pointing out the obvious
(faq)--some days I deserve to be slapped :P

-Wes
You're obviously new around here. *That* was no slap! ;-)

/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
int num_messages=0;

int main(int argc, char **argv) {
char tmpmsg[][BUFFLEN] = {"a","b","c","d ","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tm pnum);

/* first, malloc 0*sizeof(char *) bytes for messages, as we have no
pointers yet */
messages = malloc(num_mess ages*sizeof(cha r *));
Why bother? Leave this line out.
/* Do the copy loop */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocat ing space for %d.\n",x);
if ( (messages = realloc(message s, (num_messages+1 )*sizeof(char *)))
== NULL)
Though it's not applicable here (as receiving a NULL from realloc will
lead to an immediate exit, as per the code below), you should assign the
return value of realloc() to a temporary variable, just in case it
fails. Otherwise (assuming your program can continue) you've created a
memory leak as you've lost the pointer to the original buffer.

Also, instead of using `sizeof (char *)' use `sizeof *messages'; it's a
style issue, to be sure (and not immediately important here) but it
helps in cases where the type you're allocating may change [it's always
preferable to have to make as few changes as possible when something,
well, changes.]
{
printf("Could not allocate space for one more pointer.\n");
return 1;
}
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))
==NULL) Don't cast the return value of malloc(). It's unnecessary and can hide
errors. {
printf("Could not allocate space.\n");
return 1;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_mess ages;x++) {
printf("%02d => %s\n",x,message s[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
Why bother? You're just about to free the space anyway!
free(messages[x]);
}
free(messages);

/* the end of the test...finally :P */
return 0;
}

You're getting there.

Cheers and HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com (new post 8/5)
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Nov 15 '05 #6
ncf
I definately chopped this up to shrink it down quite a bit, but yea, my
replies are inline.

Artie Gold wrote:
Thank you for pointing out the obvious (faq)--some days I deserve to
be slapped :P You're obviously new around here. *That* was no slap! ;-)

Hehe, no, but I practically slapped myself over some of the stupid
errors I've done. :grin:

messages = malloc(num_mess ages*sizeof(cha r *));

Why bother? Leave this line out.

Hmm...how would I do the realloc later then if the space was never
alloc'd? Or would that be unnecessary as well? :slightly confused:

if ( (messages = realloc(message s, (num_messages+1 )*sizeof(char *))) == NULL)

Though it's not applicable here (as receiving a NULL from realloc will
lead to an immediate exit, as per the code below), you should assign the
return value of realloc() to a temporary variable, just in case it
fails. Otherwise (assuming your program can continue) you've created a
memory leak as you've lost the pointer to the original buffer.

Hmm...I *think* I see what you're saying. By memory leak, I'm infering
that you mean memory that was never free()d for other applications to
use.

Also, instead of using `sizeof (char *)' use `sizeof *messages'; it's a
style issue, to be sure (and not immediately important here) but it
helps in cases where the type you're allocating may change [it's always
preferable to have to make as few changes as possible when something,
well, changes.] Heh, alrighty :) I'll try to keep that in mind next time so you don't
kill me (JPJP)

if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN)) ==NULL)

Don't cast the return value of malloc(). It's unnecessary and can hide
errors.

Hmm...I'm not too sure right now how it'd hide errors, but hey! It'll
make sense probably later on, so lets not worry too much about that.
I'll just take your word for it ;)

memset(messages[x], '\0', sizeof(messages[x]));

Why bother? You're just about to free the space anyway!

Eh, I'm one of those odd people that likes to clean stuff up after
usage. But in retrospect, wasted CPU (however little).

You're getting there.

Horray :P /Rand
Thanks AG and have a GREAT day :)
-Wes

Nov 15 '05 #7
ncf wrote:
Artie Gold wrote:
messages = malloc(num_mess ages*sizeof(cha r *));


Why bother? Leave this line out.


Hmm...how would I do the realloc later then if the space was never
alloc'd? Or would that be unnecessary as well? :slightly confused:


realloc(NULL, size) does the same thing as malloc(size),
realloc(ptr, 0) does the same thing as free(ptr).
Your implementation typically comes with a standard library
reference which you should look into; if not, try the C99
library reference on dinkumware.com
if ( (messages = realloc(message s, (num_messages+1 )*sizeof(char *))) == NULL)


Though it's not applicable here (as receiving a NULL from realloc will
lead to an immediate exit, as per the code below), you should assign the
return value of realloc() to a temporary variable, just in case it
fails. Otherwise (assuming your program can continue) you've created a
memory leak as you've lost the pointer to the original buffer.


Hmm...I *think* I see what you're saying. By memory leak, I'm infering
that you mean memory that was never free()d for other applications to
use.


Yes and no. It may be also memory _you_ cannot use later on in
your program because you already allocated but sort of lost the
key to use it. If you need large amounts of memory this may be
the bit which makes your program exit earlier than planned due
to (self-inflicted) lack of memory...
As an aside, most modern operating systems clean up after an
application finished, so many well-known applications accept
that there are memory leaks in their code that could not be
tracked down. This is bad practice and may hide other errors
which then come down as soon as some minor detail changes. Just
avoid them :-)

if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN)) ==NULL)


Don't cast the return value of malloc(). It's unnecessary and can hide
errors.


Hmm...I'm not too sure right now how it'd hide errors, but hey! It'll
make sense probably later on, so lets not worry too much about that.
I'll just take your word for it ;)


For one, it is not necessary. The other thing is that casts
are pretty strong: They tell the compiler to shut up.
In combination with the "implicit int" rule, this may shadow
the fact that you forgot to #include <stdlib.h> which in turn
can lead to odd effects if sizeof(int) is different from the
size of the respective pointer type you cast to -- it may go
well 99% of the time but every now and then, you have your
program eating your hard disc's contents or similar...

You're getting there.


Horray :P /Rand

Thanks AG and have a GREAT day :)


My, you _really_ have promise ;-)
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #8
ncf <no************ ***@gmail.com> wrote:
Alrighty, I just checked one comp.lang.c faq (located at
http://www.faqs.org/faqs/C-faq/faq/), and to be quite honest, the code
they're using is making little sense to me, but I will give it a shot.
It is proper Usenet etiquette to include 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.
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))


It isn't in the FAQ, but should be: Casting the return of malloc() is
both unnecessary and inadvisable. Read this group's archives for
details.

--
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.
Nov 15 '05 #9
"ncf" <no************ ***@gmail.com> writes:
Ok, wow, I think I get it now, but it would be grealy appreciated if
someone could look over my updated/modified code to make sure that it
does as it seems it should. Thank you for pointing out the obvious
(faq)--some days I deserve to be slapped :P
Here is my take: Your code is fine, only minor issues.

-Wes

/*
* malloc/realloc/free test
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFLEN 10

char **messages;
char **messages = NULL; /* initalize, so we can use realloc from start */
int num_messages=0;

int main(int argc, char **argv) {
int main(void) { /* here we don't use command line arguments, so void
eliminates a couple of warnings */
char tmpmsg[][BUFFLEN] = {"a","b","c","d ","e"};
int tmpnum = sizeof(tmpmsg)/BUFFLEN;

printf("Going to copy %d messages.\n",tm pnum);

/* first, malloc 0*sizeof(char *) bytes for messages, as we have no
pointers yet */
/* Remove this:
messages = malloc(num_mess ages*sizeof(cha r *));
*/

/*
* I (and many with me) prefer the style: ptr = malloc(count * sizeof *ptr);
* That works all the time, is always the same (you don't need to think of the
* type at all), but here you don't need malloc at all, since you don't need
* any memory yet, but just a defined starting point for later calls to realloc.
* Setting messages = NULL is enough. (Calling realloc with a NULL ptr is
* exactly the same as calling malloc).
*/

/* Do the copy loop */
{ /* in C90 variable declarations must only appear before executable code
this has changed in C99, but must people still use C90 compilers */
int x;
for (x=0; x<tmpnum; x++) {
printf("Allocat ing space for %d.\n",x);
if ( (messages = realloc(message s, (num_messages+1 )*sizeof(char *)))
== NULL)
/* Style: */ messages = realloc(message s, num_messages + 1 * sizeof *messages);

/* Also notice that if you need somewhat more sofisiticated error handling
* you lose the original buffer if realloc fails. In that case you need to do
* something like:
* tmp = realloc(...);
* if (tmp == NULL) {
* error_handling( ...);
* free(messages) /* or maybe not, depending on everything else */
* return, abort, exit or something perhaps
* }
* messages = tmp;
*/
{
printf("Could not allocate space for one more pointer.\n");
return 1;
return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */
}
if ( (messages[num_messages] = (char *)malloc((size_ t)BUFFLEN))
==NULL)
/* Unnecessary casts, I'd say: */
if ((message[num_messages] = malloc(BUFFLEN) ) == NULL)

{
printf("Could not allocate space.\n");
return 1;
return EXIT_FAILURE;
}

strcpy(messages[num_messages], tmpmsg[x]);
num_messages++;
}

/* print all the values */
for (x=0;x<num_mess ages;x++) {
printf("%02d => %s\n",x,message s[x]);
}

/* clear and free all the positions of memory */
for (x=num_messages-1;x>=0;x--) {
memset(messages[x], '\0', sizeof(messages[x]));
free(messages[x]);
}
free(messages);
} /* end of local block for int x; */

/* the end of the test...finally :P */
return 0;
}

Nov 15 '05 #10

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

Similar topics

14
7947
by: Joseph | last post by:
I am trying to create a function that allocates memory for the matrix through a function; like the code below. However, this does not seem to work since I believe that the scope of the memory allocation only lasts within the create function. Is there anyway around this? Thanx in advance. I also DON'T want to declare int **matrix globally. int main(void) { int **matrix;
8
2262
by: Pegboy | last post by:
I am having trouble with malloc() again for a PC app I am developing. The method of the suspicious line of code seems to be Ok on a embedded platform, but not with the PC platform. The embedded platform uses a different compiler. I feel like I'm overlooking a very simple problem, but I can't see it. I would appreciate any help. Thank you. I am trying to allocate memory for a structure of type NAT_S which contains a pointer to a...
11
1645
by: Gustavo G. Rondina | last post by:
Hi all I'm writting a simple code to solve an ACM problem (http://acm.uva.es, it is the problem #468). In its code I have the following fragment: freq = calcfreq(hashfreq, strfreq, input); printf("before malloc: %s (%p)\n", input+INPUTLEN); hchars = (char *)malloc(freq*sizeof(char)); schars = (char *)malloc(freq*sizeof(char));
35
2709
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
11
5801
by: lohith.matad | last post by:
Hi all, Though the purpose of both malloc() and calloc() is the same, and as we also know that calloc() initializes the alloacted locations to 'zero', and also that malloc() is used for bytes allocation whereas calloc() for chunk of memory allocation. Apart from these is there any strong reason that malloc() is prefered over calloc() or vice-versa? Looking forward for your clarrifications , possibly detailed.
15
2591
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that malloc always returned null at this moment and the program exited (even though if I malloc'ed only 20 bytes or something)... Then I googled for this problem and found something about a memory pool??? Is that standard C? I didn't understand it,...
68
15716
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting; some may find it off-topic or confusing. Disclaimers at end. The code samples are intended to be nearly minimal demonstrations. They are *not* related to any actual application code.
25
2266
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking. --- #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct {
71
19136
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a problem? I cannot see why using malloc instead of new does not give the same result.
0
10161
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
8986
agi2029
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...
1
7506
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
6743
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
5390
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
5523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4058
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
3662
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2890
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.