1

I would like to write a function in C that truncates an input string to 32 chars, but the code below gives me a segmentation fault. Could anyone explain why it is so?

void foo (char *value){
    if (strlen(value)>32) {
        printf("%c\n", value[31]); // This works
        value[31] = '\0';          // This seg faults
    }
}
dbush
  • 205,898
  • 23
  • 218
  • 273
Hui Wang
  • 131
  • 6

2 Answers2

6

If you call your function like this:

char str[] = "1234567890123456789012345678901234567890";
foo(str);

It will work fine. But if you call it like this:

char *str = "1234567890123456789012345678901234567890";
foo(str);

That can cause a segfault.

The difference here is that in the former case str is a char array, while in the latter case str is a pointer to a string constant. A string constant typically lives in a read only section of memory, so attempting to modify it causes the core dump.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • @HuiWang Glad I could help. Feel free to [accept this answer](http://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush Mar 12 '17 at 13:25
0

Your program should be something like this :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void foo(char **value) {
    if (strlen(*value)>32) {
        printf("%c\n", (*value)[32]);
        (*value)[32] = '\0'; // You want the string length to be 32, so set 32th character to '\0' so 32 characters will be from 0 to 31
    }
}

int main() {
    char *str;
    str = malloc(100); // Change 100 to max possible length of string user can enter

    printf("Enter string : ");
    scanf("%s", str);

    foo(&str);

    printf("Truncated string is %s\n", str);

    free(str);

    return 0;
}
androidFan
  • 611
  • 2
  • 19
  • 31
  • 1
    This is exactly one of the reasons why you [should not cast the result of `malloc`](http://stackoverflow.com/q/605845/3049655). See the last bullet point of [this answer](http://stackoverflow.com/a/605858/3049655). You forgot to include `stdlib.h` and the cast hides the error. Also, `free` the memory (although it would automatically be freed in this case as the program ends) – Spikatrix Mar 12 '17 at 04:30
  • @CoolGuy since C99 the cast does not hide the error – M.M Mar 12 '17 at 04:39
  • Important thing to note here is that you have to cast for C++ – androidFan Mar 12 '17 at 04:41
  • @M.M Thanks for letting me know! :-) – Spikatrix Mar 12 '17 at 05:57