I am trying to create a function guilabel_wrap(char *buffer, int maxlen) that takes a pointer to a string and a length, then modifies the string to insert \n so that the string never exceeds the length, such that
char* guilabel = "Hello, world! How are you doing?";
guilabel_wrap(guilabel, 15);
printf("%s", guilabel);
will print
Hello, world!
How are you
doing?
I’ve come up with the function below, which compiles with gcc, but results in a segmentation fault. I suspect that the issue is with the 2nd while loop and a failure of my understanding of pointers.
void guilabel_wrap(char* buffer, int maxlen) {
char *pos;
char *end;
pos = buffer;
end = (pos + strlen(buffer));
while ((end - pos) > maxlen) {
pos += maxlen;
while (isspace(*pos)) {
--pos;
if (pos < buffer)
return;
}
*pos = '\n';
}
}
edit: I’m calling this function using an argument from another function. It looks like this:
dia_yesno("Hello, world! How are you doing today? I'm doing well");
which is declared as bool dia_yesno(char* guilabel). Then, within dia_yesno(), I call guilabel_wrap(guilabel, 15) as described above.
Your string constant is probably in a read-only area of memory, which is why you are getting the segmentation fault. This can be demonstrated by trying to run the following code:
You should create a buffer large enough to hold your string, plus the additional
'\n'characters, and copy your string into that first. Declaring your string as an array will also fix the problem, such as: