Home > Back-end >  Segmentation fault and 'free' called on a pointer to an unallocated object
Segmentation fault and 'free' called on a pointer to an unallocated object

Time:11-01

I am currently writing a program to simply reverse a string in C. However, when I try to copy the contents of the temp string I made into the original string, I get a segmentation fault. Also, when I try to free the memory I allocated for my test string I get a warning which says " 'free' called on a pointer to an unallocated object " Here is my code:

void reverseString(char* str, size_t size) {
    char *temp = (char*) malloc(sizeof(str)   1);
    int j = size;
    for (int i = 0; i < size; i  ) {
        temp[i] = str[j];
        j--;
    }
    for (int i = 0; i < size; i  ) {
        str[i] = temp[i];
    }

    free(temp);
    return;
}


int main() {
    char* result = (char*)(malloc(sizeof(char) * 10));
    result = "Forty-two";

    reverseString(result, strlen(result));

    printf("%s", result);

    free(result);
    result = NULL;

    return 0;
}

CodePudding user response:

On the second line, you should be using strlen instead of sizeof, because otherwise you will be allocating space for a character pointer and you need more than that.

CodePudding user response:

  • sizeof(str) returns size of pointer not length of the literal.
  • Array index starts from 0. That's why j should starts with (size - 1)
  • You are allocating memory from heap, use memset before do something.

@bereal already says, if you want to understand more, please check this out :

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

int main() {
    char* result = (char*)(malloc(sizeof(char) * 10));
    memset(result, 0, 10);

    printf("Addr of result var : %p \n", result);

    result = "Re-assign";

    printf("Addr of result var : %p \n", result);
    return 0;
}

Maybe my solution gives an idea for you

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

void reverseString(char** str, size_t size) {
    char *temp = (char*) malloc(size   1);
    memset(temp, 0, size   1);
    int j = size - 1;
    for (int i = 0; i < size; i  ) {
        temp[i] = str[0][j];
        j--;
    }

    //Change addr of holding str
    *str = temp;

    return;
}


int main() {
    char* result = "Forty-two";

    reverseString(&result, strlen(result));

    printf("%s", result);

    //result holds same addr with temp
    free(result);

    return 0;
}

But there are ways to solve this question more accurately.

  •  Tags:  
  • c
  • Related