I have a very simple program but this is giving me a seg fault. I have been struggling from a long time to figure this out. Please help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
main() {
char *database;
int ndata=4;
database="aaa4baa3bcd2aab5";
char *dummy;
dummy=(char *)malloc(16);
memcpy(dummy,database,16);
printf("%s\n",dummy);
std::swap(database,dummy);
dummy[2]='a';
}
Assigning to the dummy variable before the swap works fine. What is the problem after the swap.
thanks
I’ll rewrite your code a bit without changing its meaning
after you’ve done
swapdummypoints wheredatabasepointed previously and that’s an address of a string literal which you are not allowed to modify.Also please note that the string literal has 16 characters plus a null terminator – total 17 characters, so once you’ve allocated the buffer of size 16 and copied the literal there the result is not null terminated.