Hi all, I have virtually no knowledge of C, but I have a problem with one of my scripts. It runs fine on a 64-bit Linux machine, yet it gives me a seg fault when run on 32-bit linux. gdb tells me that the seg fault occurs on line 314.

Here is the relevant section of code:

304        #define VSN_BUF_SIZE 1000
305        char* buffer = NULL;
306        buffer = (char *)malloc(sizeof(char) * (VSN_BUF_SIZE+1));
307        if (level > stdio_level && level > log_level)
308        {
309                free (buffer);
310                return 0;
311        }
312        
313        //  Seg fault occurs here: 
314        int count = vsnprintf(buffer,VSN_BUF_SIZE, format, ap);

Running through gdb from line 305, I get this:

(gdb) break script.c:305
(gdb) run
Starting program: /home/bin/script.c
305   in script.c 
(gdb) print buffer
$15 = 0xb7ea2720 ""
(gdb) n
306 in script.c
(gdb) print buffer
$16 = 0x0
(gdb)

The value of buffer at line 306 is 0x0, which is the NULL pointer. This is not what should happen, is it? - the buffer should point to the memory allocated on line 305, right?

I think the issue may be with malloc on line 306. If malloc returns NULL does that mean it cannot allocate the amount of memory requested?

Can someone please help me out here?

Yes, malloc() returns NULL if the allocation failed. Did you include stdlib.h? Your cast of the pointer from malloc, is unnecessary in C, and will prevent the compiler from issuing an error regarding this oversight with stdlib.h.

I don't believe 1000 char's is too much, but check the other variable values to ensure that the buffer is not being freed, etc.

You want to check the pointer address at 307, not at 306, in your debugger. It will still be NULL until AFTER malloc returns the proper address, at the end of line 306, not at the start.

Good points by Adak.

I'd like to add that, why not simply check what malloc() returns, along the lines of ..

buffer = malloc(VSN_BUF_SIZE + 1);

if(buffer == NULL)
{
  /* Display error message and perhaps exit */
  perror("malloc()");
  exit(EXIT_FAILURE);
}

In case the reason is not an allocation failure, then you might post more code. Preferably a minimal complete example which still fails.

PS. Note that sizeof(char) is guaranteed to yield 1, so using it is redundant.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.