tproger
tproger

Reputation: 77

Passing a string to a function with pointer / C

I want to pass this in my function, but something is going wrong

FILE *f = fopen("out.bmp", "rb");
    int countBit = 0;
    int size = 0;
    char* type;

    for (int i = 0; i < 54; i++)
        fgetc(f);
    printf("/* count bit to pixel */\n");
    scanf("%d", &countBit);
    size=DecodeInformationSize(f, countBit);
    type=DecodeInformationType(f, countBit);
    DecodeMessage(f,countBit,size,type);

before entering the function type is txt enter image description here

but after :

void DecodeMessage(FILE *f, int countBit, int size, char* type)
{
    char messageSize[8];
    char nameOut[15] = "outMessage.";
    strcat(nameOut, type);
    char* message = (char*)malloc(size * 8);

enter image description here

please explain problem

Upvotes: 0

Views: 47

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

To be absolutely sure we need to know what DecodeInformationType(f, countBit); does.

However, it seems it uses some data on the stack. Once it returns, this information may only be available for a few instructions. So your debugger shows that the call to DecodeMessage, type points to a valid string, but once you enter DecodeMessage, the stack is overwritten with the variables of DecodeMessage, in particular with char nameOut[15] = "outMessage.";

To solve this, make sure that DecodeInformationType returns a pointer to memory that is not on the stack (not an automatic variable) of DecodeInformationType. That could be memory allocated with malloc or a constant string.

Upvotes: 1

Related Questions