Home > Back-end >  Pointer issue when using with functions in c
Pointer issue when using with functions in c

Time:10-18

i have issues with my programm.

When i launch the programm,the console don' t show the 2 numbers that it should ,instead it only shows this:

Process returned -1073741819 (0xC0000005)   execution time : 1.759 s

This is my code:

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




Test(int* Ptr)
{

    Ptr=(int*)malloc(8);

    if(Ptr==0)
    {
        printf("malloc error\n");
    }

    Ptr[0]=155;
    Ptr[1]=800;
}


int main()
{

int* m_Ptr=0;

Test(m_Ptr);

printf("%d  %d",m_Ptr[0],m_Ptr[1];

return 0

}


CodePudding user response:

With malloc(8) you request 8 bytes. On a 64bit system sizeof(int) could be 8 bytes. If so, the line

Ptr[1]=800;

actually writes to memory beyond the allocated Arena.

Try to change the malloc line to

Ptr=(int*)malloc(sizeof(int)*2)

CodePudding user response:

You're main issue is that the pointer you pass into test() is passed by copy. So m_ptr is null when its passed in and its still null when test returns.

You probably want to change your function slightly to something more like:

int* Test()
{
    int * Ptr = (int*) malloc(20);

    if(Ptr==0)
    {
        printf("malloc error\n");
    }

    Ptr[0]=155;
    Ptr[1]=800;

    return Ptr; // Return the pointer by value
}

And use like (in main):

int* m_Ptr = Test(m_Ptr);
// Now m_Ptr actually points to something...

CodePudding user response:

The argument Ptr in test is a different object in memory from m_Ptr in main - any changes to test::Ptr (such as assigning it the result of malloc) are not reflected in main::m_Ptr. You will either have to pass a pointer or a reference to m_Ptr to test, or test will have to return a pointer value that you assign to m_Ptr:

m_Ptr = Test(); // returns pointer to newly allocated memory.

If this is meant to be C , then don't use malloc (or calloc, or realloc). Either use a standard container like a vector or set (which automatically grow as new items are added), or use the new operator to manually allocate memory to some kind of smart pointer. Don't use C-style memory management in C code; it's labor-intensive, it's unsafe, and it's easy to get things wrong.

  • Related