473,545 Members | 2,688 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

segmentation fault, malloc error

Dear all,

I am new to C and I have a problem with "segmentati on 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 2394
ma************@ gmail.com wrote:
Dear all,

I am new to C and I have a problem with "segmentati on 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(nb Vert*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(nb Vert*sizeof(int ))) == 0)
Writing it this way:

if (NULL == (TheReg = malloc(nbVert*s izeof(*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[] = "1234567890ADDR ESS-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_t erminated = 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_t erminated = 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*s izeof(*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[] = "1234567890ADDR ESS-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_t erminated = 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_t erminated = 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.goog legroups.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(nb Vert*sizeof(int ))) == 0)
exit (EXIT_FAILURE);

Nov 12 '07 #6
On Nov 12, 4:03 pm, "Lukás Polok" <xpolo...@stud. fit.vutbr.czwro te:
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(nb Vert*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_FAILI RE);

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
29666
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 function with this statement several times and seems that it has successfully allocated the memory. and then at some iteration, it just gets this...
16
8961
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 who don't speak french arbre means tree.
7
3339
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"... ;-) but this time, it's not my code who "segment fault" but it's in the call of malloc/mallopt I've got:
1
2400
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 someone take a look and tell me how to fix it - please dont be like the guy I spoke to today and tell me that I am not allocating the memory...
3
11393
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 () from /lib/tls/libc.so.6 It's really strange; I just call malloc() like "tmp=malloc(size);" the system gives me Segmentation fault I want to...
6
4756
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 fault. If I just call realloc( ) once before calling malloc( ), it is OK. Why? I am trying to read some double-typed items from infile and save them
27
3325
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! #include <stdlib.h> #include <stdio.h> typedef struct _node_t {
7
328
by: aarklon | last post by:
char *f() { char *s = malloc(8); strcpy(s,"good bye"); } int main(void) { printf("\n %s",*f()='A');
3
288
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 full C script of what I did. I would be really really appreciate your help. I need to finish this code by monday but i'm stuck at this point and...
25
3352
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...
0
7434
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...
0
7692
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. ...
1
7457
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...
0
7791
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...
1
5360
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...
0
3491
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...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1045
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
744
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...

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.