473,403 Members | 2,183 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,403 software developers and data experts.

segmentation fault, malloc error

Dear all,

I am new to C and I have a problem with "segmentation fault" occurring
unexpectedly, i.e., not immediately after a programming error. I
presume
I allocated wrongly before, but I can't find the error, after
extensive search.

This is new situation to me as the vector class of C++ and the GAP
programming language (for algebraic computation) when a seg fault
happens, the error source was rather direct.

What advice would you give for finding the bug?
C is mandatory, since extreme speed is sought.

The source is available on www.liga.ens.fr/~dutour/Sending/ForDebug.tar.gz
if you are interested in helping

Thanks in advance for any help or advice.

Mathieu

Nov 12 '07 #1
7 2387
ma************@gmail.com wrote:
Dear all,

I am new to C and I have a problem with "segmentation fault" occurring
unexpectedly, i.e., not immediately after a programming error. I
presume
I allocated wrongly before, but I can't find the error, after
extensive search.

This is new situation to me as the vector class of C++ and the GAP
programming language (for algebraic computation) when a seg fault
happens, the error source was rather direct.

What advice would you give for finding the bug?
Check out these tools: valgrind or electric-fence.

I didn't check your source, but I guess you haven't used any assert()
checks, those are very useful to track down memory faults.

--
Tor <bw****@wvtqvm.vw | tr i-za-h a-z>
Nov 12 '07 #2
Check out these tools: valgrind or electric-fence.
>
I didn't check your source, but I guess you haven't used any assert()
checks, those are very useful to track down memory faults.

--
Tor <bwz...@wvtqvm.vw | tr i-za-h a-z>
Thanks for that, I will read the manual of those programs.

I don't understand why assert is supposed to be used. man assert is
not
so helpful. Can you give me an example of use of assert for tracking
memory faults?

In my code, I put systematically the following
if ((TheReg = (int*)malloc(nbVert*sizeof(int))) == 0)
exit (EXIT_FAILURE);

Nov 12 '07 #3
ma************@gmail.com wrote:
>Check out these tools: valgrind or electric-fence.

I didn't check your source, but I guess you haven't used any assert()
checks, those are very useful to track down memory faults.

--
Tor <bwz...@wvtqvm.vw | tr i-za-h a-z>

Thanks for that, I will read the manual of those programs.

I don't understand why assert is supposed to be used. man assert is
not
so helpful. Can you give me an example of use of assert for tracking
memory faults?

In my code, I put systematically the following
if ((TheReg = (int*)malloc(nbVert*sizeof(int))) == 0)
Writing it this way:

if (NULL == (TheReg = malloc(nbVert*sizeof(*TheReg))))

is less error prone.
exit (EXIT_FAILURE);
Here is a function, not too trivial and not too difficult, and it
demonstrate usage of assert(). I left in the doxygen comments.

The idea of this function, was to pick fixed sized fields, from a buffer
like this:

char array[] = "1234567890ADDRESS-FIELD-1 ADDRESS-FIELD-2 ";

Hence, a call like

char s[40];
size_t n;
n = str_acpy(s, sizeof s, array+10, 20);

should copy "ADDRESS-FIELD-1 " into object 's' without overflow.
/**
* \fn size_t str_acpy(char *s, size_t max_s, const char *a, size_t alen)
*
* \brief str_acpy() copy array of chars 'a', into a string 's'.
* 1. always null terminate output buffer 's'
* 2. never overflow output buffer 's'
* 3. truncatination is an error.
* \param s - target buffer
* \param max_s - size of target buffer
* \param a - array of chars
* \param alen - max lenght of input array
*
* \return strlen(s)
* (size_t)-1 on input errors,
* (size_t)-2 on truncate error
*/
size_t str_acpy(char *s, size_t max_s, const char *a, size_t alen)
{
size_t i,
rc = 0;
char *dst = s;
const char *src = a;
int has_been_null_terminated = 0;

/* pre-condition */
assert(s != NULL);
assert(a != NULL);
assert(max_s 1); /* require '\0' to be written */
assert(alen 0); /* require input to have data */
assert(alen < max_s); /* overflow check */

/* run-time checks - Remark 'max_s <= alen' is omitted */
if (s == NULL || max_s < 1 || a == NULL || alen < 1)
{
rc = (size_t)-1;
}
else
{
/* do copy */
for (i=0; i<max_s && i<alen; i++)
{
if (*src == '\0')
has_been_null_terminated = 1;

*dst++ = *src++;

if (has_been_null_terminated)
break;
rc++;
}

/* always null terminate destination string,
set error on trunc*/
if ( !has_been_null_terminated)
{
if (alen < max_s)
{
s[alen] = '\0';
}
else
{
s[max_s - 1] = '\0';
rc = (size_t)-2;
}
}

}

/* post-condition */
assert(rc < max_s);
assert(rc <= alen);

return rc;
}

--
Tor <bw****@wvtqvm.vw | tr i-za-h a-z>
Nov 12 '07 #4
Thank you, valgrind already gave me good idea of the problem.

Thanks also for the assert code, I will look at how to make
the memory management correctly.

Mathieu
Writing it this way:

if (NULL == (TheReg = malloc(nbVert*sizeof(*TheReg))))

is less error prone.
exit (EXIT_FAILURE);

Here is a function, not too trivial and not too difficult, and it
demonstrate usage of assert(). I left in the doxygen comments.

The idea of this function, was to pick fixed sized fields, from a buffer
like this:

char array[] = "1234567890ADDRESS-FIELD-1 ADDRESS-FIELD-2 ";

Hence, a call like

char s[40];
size_t n;
n = str_acpy(s, sizeof s, array+10, 20);

should copy "ADDRESS-FIELD-1 " into object 's' without overflow.

/**
* \fn size_t str_acpy(char *s, size_t max_s, const char *a, size_t alen)
*
* \brief str_acpy() copy array of chars 'a', into a string 's'.
* 1. always null terminate output buffer 's'
* 2. never overflow output buffer 's'
* 3. truncatination is an error.
* \param s - target buffer
* \param max_s - size of target buffer
* \param a - array of chars
* \param alen - max lenght of input array
*
* \return strlen(s)
* (size_t)-1 on input errors,
* (size_t)-2 on truncate error
*/
size_t str_acpy(char *s, size_t max_s, const char *a, size_t alen)
{
size_t i,
rc = 0;
char *dst = s;
const char *src = a;
int has_been_null_terminated = 0;

/* pre-condition */
assert(s != NULL);
assert(a != NULL);
assert(max_s 1); /* require '\0' to be written */
assert(alen 0); /* require input to have data */
assert(alen < max_s); /* overflow check */

/* run-time checks - Remark 'max_s <= alen' is omitted */
if (s == NULL || max_s < 1 || a == NULL || alen < 1)
{
rc = (size_t)-1;
}
else
{
/* do copy */
for (i=0; i<max_s && i<alen; i++)
{
if (*src == '\0')
has_been_null_terminated = 1;

*dst++ = *src++;

if (has_been_null_terminated)
break;
rc++;
}

/* always null terminate destination string,
set error on trunc*/
if ( !has_been_null_terminated)
{
if (alen < max_s)
{
s[alen] = '\0';
}
else
{
s[max_s - 1] = '\0';
rc = (size_t)-2;
}
}

}

/* post-condition */
assert(rc < max_s);
assert(rc <= alen);

return rc;

}

--
Tor <bwz...@wvtqvm.vw | tr i-za-h a-z>

Nov 12 '07 #5
what you write is allright, but the problem is more likely that you
overwrite part of memory somewhere (by writing out of array bounds) and then
the next malloc likely fails. happens to me sometimes ...

assert is when you want to make sure something's right in your algorithm (as
can be done with if), but you don't want it to be included in release
version. example of use:

for(int i = ...; ...; i = f(i)) {
assert(i >= 0 && i < array_size); // does this cycle really work?
pointer[i] = blah; // now that i'm sure i've got the right index, i can
fearlessly do this
}

see? the idea is there's some complicated cycle (or for example index is
looked up from some table) and you're checking wheter it's working
correctly. the programmer writing this thinks it -should- work, and
therefore it's not worth if, along with an error message, etc ... but people
do mistakes and this can help find them.

good luck ...

<ma************@gmail.compíse v diskusním príspevku
news:11**********************@22g2000hsm.googlegro ups.com...
Check out these tools: valgrind or electric-fence.

I didn't check your source, but I guess you haven't used any assert()
checks, those are very useful to track down memory faults.

--
Tor <bwz...@wvtqvm.vw | tr i-za-h a-z>

Thanks for that, I will read the manual of those programs.

I don't understand why assert is supposed to be used. man assert is
not
so helpful. Can you give me an example of use of assert for tracking
memory faults?

In my code, I put systematically the following
if ((TheReg = (int*)malloc(nbVert*sizeof(int))) == 0)
exit (EXIT_FAILURE);

Nov 12 '07 #6
On Nov 12, 4:03 pm, "Lukás Polok" <xpolo...@stud.fit.vutbr.czwrote:
what you write is allright, but the problem is more likely that you
overwrite part of memory somewhere (by writing out of array bounds) and then
the next malloc likely fails. happens to me sometimes ...
Yes, it was new to me. But valgrind was helpful in finding the spot.

Otherwise, yes assert is certainly helpful in a C context.
I experienced long ago that making error messages early is a good
thing.

Mathieu

Nov 13 '07 #7
ma************@gmail.com wrote:
>
.... snip ...
>
I don't understand why assert is supposed to be used. man assert
is not so helpful. Can you give me an example of use of assert
for tracking memory faults?

In my code, I put systematically the following

if ((TheReg = (int*)malloc(nbVert*sizeof(int))) == 0)
exit (EXIT_FAILURE);
You should NEVER cast the return value from malloc. The preferred
mechanism is:

if (!(TheReg = malloc(sizeof *TheReg))) exit(EXIT_FAILIRE);

or whatever recovery mechanism you use. This avoids ever making
sizeof operand mistakes and ensures you have #include <stdlib.h>
(else error message). Also make a practice of setting freed
pointers to NULL, i.e.:

free(TheReg); TheReg = NULL;

which will catch erroneous attempts to reuse TheReg.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 17 '07 #8

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

Similar topics

9
by: Bin Lu | last post by:
I keep getting this malloc problem when my program tries to allocate memory for some pointer. The statement is like: rsv_cache = (rsvcache *) malloc (sizeof(rsvcache)); It goes through the...
16
by: laberth | last post by:
I've got a segmentation fault on a calloc and I don'tunderstand why? Here is what I use : typedef struct noeud { int val; struct noeud *fgauche; struct noeud *fdroit; } *arbre; //for those...
7
by: Alexandre | last post by:
Hello, Maybe it's a little OT, but the fact is that I don't necessarly want to know "how to correct?", but "why it happens?" I have a program who "segment fault" (ok, that's "normal"... ;-)...
1
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...
3
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc...
6
by: I_have_nothing | last post by:
Hi! I am new in C. I try to use dynamical allocation fuction malloc( ) and realloc( ). I found something strange. After several calling realloc( ), the malloc( ) will give me a Segmentation...
27
by: Paminu | last post by:
I have a wierd problem. In my main function I print "test" as the first thing. But if I run the call to node_alloc AFTER the printf call I get a segmentation fault and test is not printed! ...
7
by: aarklon | last post by:
char *f() { char *s = malloc(8); strcpy(s,"good bye"); } int main(void) { printf("\n %s",*f()='A');
3
by: Anna | last post by:
Could you please help me? I got a segmentation fault message while trying to assign a pointer = pointer like this: bufferlist=(buffer_t*)buffernew; What's the error by doing this? Here is the...
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
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
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.