This piece of code causes segmentation fault:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLIDINGWINDOW 5
#define SEGMENTSIZE 100
int main() {
char** send_buffer = (char**) malloc (SLIDINGWINDOW);
int i;
for (i = 0; i<SLIDINGWINDOW; ++i) {
send_buffer[i] = (char*) malloc (SEGMENTSIZE);
}
for (i = 0; i<SLIDINGWINDOW; ++i) {
strcpy(send_buffer[i], "Hello, world");
printf("%s\n", send_buffer[i]);
fflush(NULL);
}
}
The strange thing is if you put the content of the second loop into the first loop, it works!
Could anyone see why this happens?
Many thanks!
The size passed to
malloc()isn’t correct. You probably meant:and
This is because the argument to
malloc()is the number of bytes you’re asking for, so you need to multiply the length you want by the size of the elements.In addition, you should also check that the value returned from
malloc()isn’tNULL.Note that I’ve removed the cast from the malloc call – in C, the cast isn’t required, and can sometimes mask an error.
A further improvement would be to use
strncpy()to ensure that you’re not going to write characters after the end of the segment:Note that in the case that the source string is larger than
SEGMENTSIZE, then the destination string will not be null terminated. You can fix this with a:after the
strncpy().