CLearner
CLearner

Reputation: 17

Advice on using pointers for malloc and free

    char arr[120];
    for (k = 0; k < 120; ++k) {
        arr[k] = (char *)malloc(1);
    }
    for (k = 0; k < 120; ++k) {
        free(arr[k]);
    }

I have the above code. I was wondering why I am getting a Segmentation Fault error when I compile and run the code. Any advice for changes?

I just want to point out that the code above is for a school project.

Upvotes: 0

Views: 49

Answers (1)

Nikos C.
Nikos C.

Reputation: 51840

You are storing char* objects into an array that can only store char objects. That's undefined behavior. You need:

char* arr[120];

Upvotes: 1

Related Questions