473,606 Members | 3,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

structure malloc help

I have a structure defined as:
struct channel {
int chanid;
int channum;
char callsign[20];
char name[64];
};

I then have a global variable defined as:
static struct channel *chan=NULL;

I then malloc the space when I know the total number of rows (dynamic
variable Total_rows) I have:
if ( (chan=(struct channel*)malloc (sizeof(struct channel)*Total_ rows))
=
= NULL) {
snprintf(buf, sizeof(buf),"Ma llor Error.\n" );
free (chan);
goto out;
}

My issue as I fill the structure the program seg faults. If I change
the line to
if ( (chan=(struct channel*)malloc (sizeof(struct
channel)*Total_ rows*sizeof(str uct channel))) =
= NULL) {

It works, but I now have sizeof twice.... or if I make the Total_rows
variable 3 times as large.

Can anyone tell me what I am doing wrong?

Thanks Mike

Jul 29 '06 #1
6 5967
md****@yahoo.co m schrieb:
I have a structure defined as:
struct channel {
int chanid;
int channum;
char callsign[20];
char name[64];
};

I then have a global variable defined as:
static struct channel *chan=NULL;

I then malloc the space when I know the total number of rows (dynamic
variable Total_rows) I have:
if ( (chan=(struct channel*)malloc (sizeof(struct channel)*Total_ rows))
Don't cast malloc's return value. Its bad as it might hide a missing
#include and its not necessary in C.
=
= NULL) {
snprintf(buf, sizeof(buf),"Ma llor Error.\n" );
free (chan);
Is there a reason to free(chan) when it's NULL?
goto out;
}

My issue as I fill the structure the program seg faults. If I change
the line to
if ( (chan=(struct channel*)malloc (sizeof(struct
channel)*Total_ rows*sizeof(str uct channel))) =
= NULL) {

It works, but I now have sizeof twice.... or if I make the Total_rows
variable 3 times as large.

Can anyone tell me what I am doing wrong?
Your code that fills the struct is wrong. Or it might be wrong. Can't
say because you didn't show it.

--
Thomas
Jul 29 '06 #2
md****@yahoo.co m wrote:
I have a structure defined as:
struct channel {
int chanid;
int channum;
char callsign[20];
char name[64];
};

I then have a global variable defined as:
static struct channel *chan=NULL;

I then malloc the space when I know the total number of rows (dynamic
variable Total_rows) I have:
if ( (chan=(struct channel*)malloc (sizeof(struct channel)*Total_ rows))
=
= NULL) {
chan = malloc( Total_rows * sizeof *chan );

Don't cast the value returned by malloc -- it serves no purpose,
and can even hide compiler warnings in some cases.

Also, using "sizeof *chan" guarantees you of allocation the right
amount of space, no matter what.

snprintf(buf, sizeof(buf),"Ma llor Error.\n" );
free (chan);
If you got this far, then chan is NULL, so there's no need to free it.
goto out;
}

My issue as I fill the structure the program seg faults. If I change
the line to
if ( (chan=(struct channel*)malloc (sizeof(struct
channel)*Total_ rows*sizeof(str uct channel))) =
= NULL) {

It works, but I now have sizeof twice....

Can anyone tell me what I am doing wrong?
Somewhere else in the code, you have a buffer overflow. Probably
over the end of 'chan' but not necessarily.

Try to reduce the program to a smaller example that you can
post in its entirety, and does demonstrate the problem.

Jul 29 '06 #3

md****@yahoo.co m wrote:
>
<snip>
I then malloc the space when I know the total number of rows (dynamic
variable Total_rows) I have:
if ( (chan=(struct channel*)malloc (sizeof(struct channel)*Total_ rows))
=
= NULL) {
snprintf(buf, sizeof(buf),"Ma llor Error.\n" );
free (chan);
goto out;
}

My issue as I fill the structure the program seg faults.
<snip>
Can anyone tell me what I am doing wrong?
As it is, it doesn't look like there is anything wrong with
this code that would cause the segfault. Casting the
return value of malloc is a bad idea, using "sizeof *chan"
is cleaner, and you can probably make a more graceful
exit without the free and by doing something like
err_message = "Out of Memory"; (or using perror() and
relying on the system to set errno), but none of these
will cause the error you're describing. The fault lies
elsewhere. Here are 2 hints to find the problem, both
of these assume you are running on Linux. (I'm going
to give specific commands which work on linux, but the
2 principles will apply to any system.)

1) Let the system check memory consistency for you.
Either run your program through something like valgrind
or electric fence or use mcheck. Read the info page
for mcheck and examine /usr/include/mcheck.h. Basically,
If you add mcheck(NULL); at the start of the program
and an occasional call to mcheck_check_al l(), it will
help locate the problem.

2) Examine the stack trace to help pinpoint the problem:
% gcc -g foo.c
% gdb a.out
(gdb) run
(gdb) bt
The bt command gives a backtrace and shows the line
that was executing when the segfault occurs.

Memory errors can be a pain, and the error is usually
not where you expect it to be.

Jul 29 '06 #4
Thank you everyone. for the help.

I still have not figured out why the malloc is not correct. But I have
figured out why it is seg faulting.

It is the qsort line below. I have provided more code.

if ( (chan=malloc(si zeof(struct channel)*Total_ rows*4)) == NULL) {
cmyth_dbg(CMYTH _DBG_DEBUG, "%s [%s:%d]: (trace) -1)\n",
__FUNCTION__, __FILE__, __LINE__);
snprintf(buf, sizeof(buf),"Ma llor Error.\n" );
mvpw_add_menu_i tem(widget, buf , (void*)i, &item_attr);
goto out;
}

if
(myth_load_chan nels(&chan,mysq lptr->host,mysqlpt r->user,mysqlpt r->pass,mysqlpt r->db)
< 0) {
cmyth_dbg(CMYTH _DBG_DEBUG, "%s [%s:%d]: (trace) -1)\n",
__FUNCTION__, __FILE__, __LINE__);
snprintf(buf, sizeof(buf),"Da tabase Error. Please
check your settings\n" );
mvpw_add_menu_i tem(widget, buf , (void*)i, &item_attr);
goto out;
} /* this function fills the chan struct. */

if ((sqlprog=mallo c(sizeof(struct program)*10))== NULL) {
perror("malloc" );
cmyth_dbg(CMYTH _DBG_DEBUG, "%s [%s:%d]: (trace) -1)\n",
__FUNCTION__, __FILE__, __LINE__);
snprintf(buf, sizeof(buf),"Ma llor Error.\n" );
mvpw_add_menu_i tem(widget, buf , (void*)i, &item_attr);
free (sqlprog);
goto out;
} /* this is a program structure.

sqlcount=get_gu ide_mysql(&sqlp rog,chan,startt ime,endtime,mys qlptr->host,
mysqlptr->user, mysqlptr->pass,mysqlpt r->db); /* this fills the
program structure */

qsort(&sqlprog, sqlcount,sizeof (*sqlprog),sche dule_compare);
static int
schedule_compar e (const void *a, const void *b)
{
const struct program *x, *y;
int X, Y;

x = ((const struct program*)a);
y = ((const struct program*)b);
X = x->channum;
Y = y->channum;

if (X < Y) {
return -1;
}
else if (X Y) {
return 1;
}
else {
return 0;
}
}

Any thoughts as to what I am doing wrong with the qsort? Thank you.
-Mike

Jul 30 '06 #5

Mike wrote:
Thank you everyone. for the help.

I still have not figured out why the malloc is not correct. But I have
figured out why it is seg faulting.

It is the qsort line below. I have provided more code.
<snip>
>
qsort(&sqlprog, sqlcount,sizeof (*sqlprog),sche dule_compare);
<snip>

That should be: qsort(sqlprog, ...)
Drop the '&'.

Jul 30 '06 #6
Mike wrote:
>
I still have not figured out why the malloc is not correct. But I have
figured out why it is seg faulting.
The malloc line is correct (without the "*4"), assuming you
have #included <stdlib.h>.

But it is fragile. Please follow the advice about malloc in my
previous post.
It is the qsort line below. I have provided more code.
if ((sqlprog=mallo c(sizeof(struct program)*10))== NULL) {
perror("malloc" );
cmyth_dbg(CMYTH _DBG_DEBUG, "%s [%s:%d]: (trace) -1)\n",
__FUNCTION__, __FILE__, __LINE__);
snprintf(buf, sizeof(buf),"Ma llor Error.\n" );
mvpw_add_menu_i tem(widget, buf , (void*)i, &item_attr);
free (sqlprog);
goto out;
} /* this is a program structure.

sqlcount=get_gu ide_mysql(&sqlp rog,chan,startt ime,endtime,mys qlptr->host,
mysqlptr->user, mysqlptr->pass,mysqlpt r->db); /* this fills the
program structure */
You only allocated space for 10 structs to 'sqlprog'. How do you
make sure that 'get_guide_mysq l' does not overflow this?
>
qsort(&sqlprog, sqlcount,sizeof (*sqlprog),sche dule_compare);
Should be:
qsort( sqlprog, sqlcount, sizeof *sqlprog, schedule_compar e );

sqlprog is a pointer to the first thing you want to sort, and that is
what qsort is expecting. Not the address of a pointer to the things
to sort.

I suspect you also have an extra & in the call to get_guide_mysql ,
although it is impossible to say without seeing the explanation of
how that function works.
static int
schedule_compar e (const void *a, const void *b)
{
const struct program *x, *y;
int X, Y;

x = ((const struct program*)a);
y = ((const struct program*)b);
Useless casts. It is good to not use casts unless absolutely necessary.
Instead, write:
x = a;
y = b;

Jul 31 '06 #7

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

Similar topics

4
2470
by: Dan | last post by:
I'm trying to creat a data structure, that can be either a integer, double, string, or linked list. So I created the following, but don't know if it is the data structure itself causing problems, or something I am doing in the rest of the program. This is the data structure. struct node { char type;
4
4070
by: Aaron Walker | last post by:
I am trying to write this piece of code that reads a config file, in the format: ENTRY value and I want to read the config file, then read the "value" into the appropriate member of the following structure: struct conf_data { char *root;
6
4190
by: Eric Smith | last post by:
Is a structure containing an incomplete array as its last element (per paragraph 2 of section 6.7.2.1 of ISO/IEC 9899:1999 (E)) itself an incomplete type? That appears to be indicated by paragraph 22 of section 6.2.5. If so, that seems to make it difficult to allocate such structures, because sizeof() is not allowed on incomplete types (paragraph 1 of section 6.5.3.4). For instance, I've routinely done things like this: struct foo {...
11
2400
by: Mannequin* | last post by:
Hi all, I'm working on a quick program to bring the Bible into memory from a text file. Anyway, I have three questions to ask. First, is my implementation of malloc () correct in the program to follow? Second, have I correctly passed the structure's pointer to the functions in this program?
18
1575
by: Chris R. | last post by:
Hi everyone. I am trying to finish my homework, but I seem not to figure out how to fix this structure that seems to make wrong output. What this program should do is use structure to save the word and line number on which it was in array pointer using malloc and print them out alphabetized (no duplicates). Most of it works, except the words seem to be corrupted. Here is a code, if anyone can help me it would help so much since I've...
13
7280
by: John | last post by:
In the course of an assignment, I learned the hard way that I shouldn't try to free a malloc'd member of a malloc'd structure after having freed that structure (i.e., free( structure ); free( structure->bufferspace ) ). My question is, if I free just the structure, will the (e.g.) bufferspace be freed implicitly, or do I have to (as I currently am) free the members first? Thanks. -cjl
5
2307
by: caleb.vandyke | last post by:
I am working with some code that is doing some pointer to structure casts and I can't figure out how the cast is being done. Here is basically the code. #include <stdio.h> #include <stdlib.h> typedef struct diffRecord { struct record *next;
22
2909
by: friend.05 | last post by:
typedef struct { int a; int b; int c; } ABC; typedef struct { int d;
25
3365
by: jbholman | last post by:
I am pretty new to C and doing my first project in C. I actually read almost the entire FAQ, but can't seem to figure out this problem. I have a structure. I have a list of these structures. Inside each structure, I have two members: a list of strings, and a string. I have made a sample program below that exhibits the error I am having. I also read about Valgrind, and used it to tell me where I was getting the segmentation fault,...
0
8036
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
7978
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
8461
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
8448
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
8126
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
8317
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
5987
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
3948
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
4010
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.