473,404 Members | 2,174 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

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),"Mallor 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(struct 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 5956
md****@yahoo.com 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),"Mallor 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(struct 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.com 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),"Mallor 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(struct 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.com 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),"Mallor 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_all(), 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(sizeof(struct channel)*Total_rows*4)) == NULL) {
cmyth_dbg(CMYTH_DBG_DEBUG, "%s [%s:%d]: (trace) -1)\n",
__FUNCTION__, __FILE__, __LINE__);
snprintf(buf, sizeof(buf),"Mallor Error.\n" );
mvpw_add_menu_item(widget, buf , (void*)i, &item_attr);
goto out;
}

if
(myth_load_channels(&chan,mysqlptr->host,mysqlptr->user,mysqlptr->pass,mysqlptr->db)
< 0) {
cmyth_dbg(CMYTH_DBG_DEBUG, "%s [%s:%d]: (trace) -1)\n",
__FUNCTION__, __FILE__, __LINE__);
snprintf(buf, sizeof(buf),"Database Error. Please
check your settings\n" );
mvpw_add_menu_item(widget, buf , (void*)i, &item_attr);
goto out;
} /* this function fills the chan struct. */

if ((sqlprog=malloc(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),"Mallor Error.\n" );
mvpw_add_menu_item(widget, buf , (void*)i, &item_attr);
free (sqlprog);
goto out;
} /* this is a program structure.

sqlcount=get_guide_mysql(&sqlprog,chan,starttime,e ndtime,mysqlptr->host,
mysqlptr->user, mysqlptr->pass,mysqlptr->db); /* this fills the
program structure */

qsort(&sqlprog,sqlcount,sizeof(*sqlprog),schedule_ compare);
static int
schedule_compare (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),schedule_ 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=malloc(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),"Mallor Error.\n" );
mvpw_add_menu_item(widget, buf , (void*)i, &item_attr);
free (sqlprog);
goto out;
} /* this is a program structure.

sqlcount=get_guide_mysql(&sqlprog,chan,starttime,e ndtime,mysqlptr->host,
mysqlptr->user, mysqlptr->pass,mysqlptr->db); /* this fills the
program structure */
You only allocated space for 10 structs to 'sqlprog'. How do you
make sure that 'get_guide_mysql' does not overflow this?
>
qsort(&sqlprog,sqlcount,sizeof(*sqlprog),schedule_ compare);
Should be:
qsort( sqlprog, sqlcount, sizeof *sqlprog, schedule_compare );

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_compare (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
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,...
4
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...
6
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...
11
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...
18
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...
13
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(...
5
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> ...
22
by: friend.05 | last post by:
typedef struct { int a; int b; int c; } ABC; typedef struct { int d;
25
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. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...
0
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,...
0
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...

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.