简体   繁体   中英

Why does my struct disapear after printing it's content?

I'am working on a project for my programming class (teoretically in C++ but our professor isn't big fan of C++ solutions and C is better viewed by him). The project is to do simple queue with type given by user and the problem is with the following code:

#include <cstdlib>
#include <cstring>
#include <stdio.h>

typedef struct
{
    int nKey;
    int* pTab;
}Usertype;

Usertype* AllocateUsertype( );
void PrintUsertype( Usertype* pItem );

int main()
{
    Usertype *pItem = AllocateUsertype();
    printf( "nKey: %d, pTab: %d %d", pItem->nKey, pItem->pTab[0], pItem->pTab[1] );
    pItem->nKey = 3;
    PrintUsertype( pItem );
}
Usertype* AllocateUsertype( )
{
    Usertype* pItem = NULL;
    int* t = NULL;
    t = (int*)malloc( 2*sizeof( int ) );
    if( !t ) return NULL;
    memset( t, 0, 2*sizeof( int ) );
    Usertype Item = { 0,t };
    pItem = &Item;
    return pItem;
}
void PrintUsertype( Usertype* pItem )
{
    printf( "nKey: %d, pTab: %d %d", pItem->nKey, pItem->pTab[0], pItem->pTab[1] );
}

When I allocate usertype it works well and the pItem is created as expected, but after I printf it it's seemes like pItem is no longer there and there's just garbage nKey number and there isn't any tab.

Is this problem because im allocating this data struct in memory wrongly and somehow t as a local variable for AllocateUsertype disapears at random moment? If yes can someone give me idea how to do it correctly?

As pointed out in the comments, the problem is that inside AllocateUsertype() you are returning a pointer to a local variable that won't exists anymore once the function returns.

The solution is to allocate a Usertype using malloc , just like you did for t , and then return its pointer.

Usertype* AllocateUsertype( )
{
    Usertype* pItem = NULL;
    pItem = (Usertype*)malloc(sizeof(Usertype));
    if (!pItem) return NULL;

    int* t = NULL;
    t = (int*)malloc( 2*sizeof( int ) );
    if( !t ) return NULL;
    
    memset( t, 0, 2*sizeof( int ) );
    pItem->nKey = 0;
    pItem->pTab = t;
    return pItem;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM