I am getting SIGSEGV error in this code and I am unable to figure out
it.
Let us first explain what segmentation fault is.
Segmentation fault
The access violation is a trap (system exception/fault) that results when process tries to access invalid memory address: either it tries to write read-only memory or process is not allowed to address this memory at all, including dereferencing null pointers and addressing non-existent memory address (this can be manipulated using for example mmap). A SIGSEGV signal ( 11) is sent on such occasions to offending process.
On the hardware level segmentation fault is implemented as an action raised by a memory management unit as a part of memory protection feature. This computer hardware unit can be a separate integrated circuit or can be placed on same IC as CPU, as in modern computers, microprocessors.
To find a line in program code that causes SIGSEGV we should look into stack trace / stack window, etc. We can put also a breakpoint before a line that caused this and investigate the program state. If the core has been dumped we can also look at this.
There is a grsecurity set of patches for Linux that increases protection against buffer overflows, stack overflows, etc. for web servers.
malloc
Standard function malloc()
, which on my implementation is declared as
/* Allocate SIZE bytes of memory. */
extern void *malloc (size_t __size) __THROW __attribute_malloc__ __wur;
takes as its argument the number of bytes to allocate.
C Standard § 7.20.3.3 The malloc function
Synopsis 1
include stdlib.h
void *malloc(size_t size);
Description
2 The malloc function allocates > space for an object whose size is specified
by size and whose value is indeterminate.
Returns
3 The malloc
function returns either a null pointer or a pointer to the allocated
space.
This means that here
m = (long long int*) malloc(n+1);
you are allocating n+1 bytes, but you need (n+1)*sizeof(long long int)
bytes to store n+1
variables of type long long int
, therefore you should write:
m = malloc( ( n + 1) * sizeof( long long int));
or better
m = malloc( ( n + 1) * sizeof *m)
^
// in C cast should be omitted ( it is still needed if you want your code
// to compile with a C++ compiler)
// sizeof *m can be used as () are needed only for a type names
https://stackoverflow.com/a/605858/1141471