Segmentation fault on strcat()
I have this c++ code:
Code:
#include <stdio.h> Code:
char *message = (char*)malloc(512); |
Code:
message = "first string\n"; Code:
char *message = (char *)malloc(512); |
In the first case, you are trying to append to a constant string. The details depend on your compiler but maybe the string was statically allocated in non-writable memory, or maybe the memory after the first string is either invalid or in use by something else.
In the second case you are using a C-string which has not been initialized. There is no guarentee that malloc will return memory with a zero in the first byte. I highly recommend that you use the c++ stl strings instead. They will handle the buffer allocation for you. |
char *message = (char *) malloc(strlen("first string\n") + 1);
is a handy way of malloc'ing some space for strings, what itsme86 said looks to me as though it should work fine. |
Here's the c++ way to do it:
#include <iostream> #include <string> using namespace std; int main() { string first("first string\n"); cout << first; first += "second string\n"; cout << first; } If you need to get a so-called C-string (really a char array) then you can use the first.str() method. |
Quote:
EDIT: Also, don't forget that you need to allocate room for the '\0' so you'd need to malloc(strlen(str)+1) bytes instead of malloc(strlen(str)) bytes. |
Quote:
|
As a completely unneeded point, if you need to malloc a copy of a string you can use strdup() instead of malloc(), strlen(), and strcpy(). It saves you from forgetting that +1 :)
|
And don't cast the return value of malloc. It's not necessary in C for the code to compile, but doing so may hide a diagnostic if you've failed to include the proper header for malloc (or another that includes it), namely <stdlib.h>. In C++ there's no automatic conversion from void*, so a cast is necessary but you should never use malloc()/free() with C++ because it doesn't know about constructors/destructors.
|
All times are GMT -5. The time now is 03:50 PM. |