473,796 Members | 2,586 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
27 1940
ncf wrote:
Michael Mair wrote:
My, you _really_ have promise ;-)


Not really sure what you mean by "you _really_ have promise", but uhh,
ok :P (bad grammar constructs seem to make me get all confused easily)


You not only took the advice and followed it but also
thanked the one giving it...

-Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #21
Michael Mair wrote:
ncf wrote:
Michael Mair wrote:
My, you _really_ have promise ;-)

s/have/show/

Not really sure what you mean by "you _really_ have promise", but uhh,
ok :P (bad grammar constructs seem to make me get all confused easily)


You not only took the advice and followed it but also
thanked the one giving it...

-Michael

--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #22
ncf wrote:
Flash Gordon wrote:
However, if the variables were moved in to main (which would be
better style since using globals where they are not needed is bad style
and a very bad habit, then it would need initialising.


The code I'm working with right now has messages and num_messages in
the file scope because I'm going to be integrating the concepts/product
of this efforts into a larger thing that I'm trying to do, so IMHO,
it's ok in this case if those two were defined global.


IMHO if it will be integrated in to a larger project that is an even
bigger reason to *avoid* using globals. I'll repeat that in general
globals are a bad idea. To provide a couple of reasons:
They provide non-obvious coupling between functions
The prevent you from reusing the function on a different piece of data

I'm not saying they should *never* be used, but something like a count
of messages does not sound to me like an appropriate use. After all, one
day you might want to have two sets of messages each with it;s own
num_messages.
return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */


I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


What's the big diff between EXIT_FAILURE and 1?! I mean, returning 1
just means generic error in the first place....


No, under VMS 1 means success. The *only* portable values are those
quoted above, 0, EXIT_SUCCESS and EXIT_FAILURE. So if your program is
going to produce only one failure code you should use EXIT_FAILURE.

There are valid reasons for using non-portable return values (for
example when you need to flag different kinds of failure), but in that
case you should not use magic numbers but either enums of #defines so
that they can easily be changed when porting to other systems.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #23
"Mike Wahler" <mk******@mkwah ler.net> writes:
"ncf" <no************ ***@gmail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
Mike Wahler wrote:
> What's the big diff between EXIT_FAILURE and 1?!

EXIT_FAILURE is portable, 1 is not.
Standard C defines exactly three values for the return
value of main:

EXIT_SUCCESS
EXIT_FAILURE
zero (0) (or any integer expression which evaluates to zero)

0 also means 'success', but note that its actual value
need not be zero (but it often is).


What I meant to say here is that although both
zero and 'EXIT_SUCCESS' designate 'successful
completion', the value of 'EXIT_SUCCESS' may
or may not be zero.

(Also note that even if main() returns zero, that
need not be the value received by the calling
environment. The implementation might translate
it to something more meaningful to that environment).


And just to make it clear that this is more than just theoretical, VMS
(now called OpenVMS) defines any odd number as a successful status,
and any even number as a failure indication. The C implementation
translates exit(0) to return a status of 1, but it doesn't translate
any other values. So a program that does exit(0), exit(EXIT_SUCCE SS),
or exit(EXIT_FAILU RE) will behave as expected, but exit(1) will
indicate that the program succeeded. (I think EXIT_FAILURE may be
defined as 2, but I wouldn't bet on it.)

The fact that EXIT_SUCCESS isn't necessarily 0 may be just
theoretical, though; I've never heard of an implementation with
EXIT_SUCCESS != 0.

In some ways, it might have been clearer for the C standard only to
define the behavior of EXIT_SUCCESS and EXIT_FAILURE, leaving 0
implementation-defined.

--
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.
Nov 15 '05 #24
ncf wrote:
Flash Gordon wrote:

0, EXIT_OK, and EXIT_FAILURE */

I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.

What's the big diff between EXIT_FAILURE and 1?! I mean, returning 1
just means generic error in the first place....


EXIT_FAILURE has a standardly defined meaning as an argument to exit(),
as do 0 and EXIT_SUCCESS. On the other hand, 1 as an argument to exit()
does not have a standardly defined meaning, and it damn sure doesn't
mean "generic error in the first place."
Nov 15 '05 #25
ncf
> >>> My, you _really_ have promise ;-)
s/have/show/

Not really sure what you mean by "you _really_ have promise", but uhh,
ok :P (bad grammar constructs seem to make me get all confused easily)


You not only took the advice and followed it but also
thanked the one giving it...


Heh, thankee. I'd much rather say thank you than to not say it and
leave my appreciation unknown. :)

Have a GREAT day :)
-Wes

Nov 15 '05 #26
Martin Ambuhl wrote:
ncf wrote:
Flash Gordon wrote:


0, EXIT_OK, and EXIT_FAILURE */

I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


What's the big diff between EXIT_FAILURE and 1?! I mean, returning 1
just means generic error in the first place....

EXIT_FAILURE has a standardly defined meaning as an argument to exit(),
as do 0 and EXIT_SUCCESS. On the other hand, 1 as an argument to exit()
does not have a standardly defined meaning, and it damn sure doesn't
mean "generic error in the first place."


Has it been noted recently that an arbitrary C program is often a
function called by the Unix shell in a program of its own?

By convention the shell, if it cares, will check the return value of the
function. Again, by convention, integer 0 indicates success and other
values indicate other things.

In any case, the return value of a C program is defined in the contract
between the C program and the shell program that called it. In other
words Implementation Specific.

Unhappily, the C Standard divorces itself from the Unix shell and does
not elaborate on the possible return values of a C programm beyond
EXIT_SUCCESS, 0 and EXIT_FAILURE.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 15 '05 #27
Flash Gordon <sp**@flash-gordon.me.uk> writes:
Niklas Norrthon wrote:
"ncf" <no************ ***@gmail.com> writes:

return EXIT_FAILURE; /* Only defined return codes from main are
0, EXIT_OK, and EXIT_FAILURE */


I think you mean EXIT_SUCCESS rather than EXIT_OK. It should also be
noted that returning 0 is defined as meaning success.


You are right of course. Personally I am usually too lazy to type it out,
so I use the zero for indicating success. Perhaps thats why my mind slipped.

Furthermore I'd say it's perfectly acceptable to use other return than
these, when coding for a specific platform where such return codes
make sense, and can carry additional information to the calling program,
(as long as one does not post such code in this forum)

/Niklas Norrthon

Nov 15 '05 #28

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

Similar topics

14
7949
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
15718
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
19141
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
10242
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
10200
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
10021
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
9061
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
7558
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
6800
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
5453
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2931
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.