Cannot cast void pointer returned by calloc

i really dont know whats going on here im trying the convert the void pointer that is returned by the calloc function if the memory allocation is succesfull to a type of reservation that is a structure that i created. the problem is when i run the program it just hangs and dose not print anything and shows the message dont send... here is the code of the program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

// Creating a structure named reservation and creating the data members that are needed.
struct reservation{
    string passengerName;
    string passengerAddress;
    string dateOfFlight;
    string desToTravel; // "des" stands for destination.
    int flightNo;
    int seatNo;
}*ptr;

main(){

    ptr = (reservation*) calloc(1,sizeof(reservation));

    if(ptr == NULL){
        cout << "Memory allocation failed.";
        exit(1);
    }

    ptr->passengerName = "This";

    cout << ptr->passengerName;

    free(ptr);

}
C memory allocation and C++ objects generally don't mix well, as the constructor is not called.

This would have been correct:

1
2
3
4
5
int main() {
    reservation res;
    res.passengerName = "This";
    cout << res.passengerName;
}


or if you truly want dynamic allocation for whatever reason:

1
2
3
4
5
6
int main() {
    ptr=new reservation;
    ptr->passengerName = "This";
    cout << ptr->passengerName;
    delete ptr;
}
ah i see thanks i needed dynamic allocation because im doing a assignment that says i have to use it.
This is a good one.

In fact, the problem isn't "Cannot cast void pointer". Why not?
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
main(){

    ptr = (reservation*) calloc(1,sizeof(reservation));

    if(ptr == NULL){
        cout << "Memory allocation failed.";
        exit(1);
    }

    ptr->seatNo = 2;

    cout << ptr->seatNo;

    free(ptr);

}


You're able to see the seatNo, aren't you? Of course, we have segfault again in free().
Why is that?


That is because the real problem is about the incompatibility between calloc and string.
calloc is for C and string is for C++.

Solution:
1, do it in the C way: get rid of string and manually allocate memory for cstrings
2, do it in the C++ way: use new and delete




Topic archived. No new replies allowed.