Agniva Dutta
Agniva Dutta

Reputation: 33

What is the reason of the exception?

Can anyone find out the reason of the error? The code is below.

#include <stdio.h>
#include <conio.h>
#include <string.h>

int main(int argc, char *argv[]){
    strcat(argv[1], ", Agniva welcomes you");
    printf("%s", argv[1]);
    getch();
    return 0;
}

Actually the program will modify the argv[1] parameter (which is a name say) which is called by another program as call by reference.

BUT I am getting

Unhandled exception at 0x00007ffd21d41cd0 in greet.exe: 
0xC0000374: A heap has been corrupted.

But if I take an extra parameter through command line which is not needed then this error gets vanished. Can you say which is making problem here?

Upvotes: 0

Views: 84

Answers (3)

asio_guy
asio_guy

Reputation: 3767

You have no way of knowing how much of a memory is allocated for argv[1] yet still trying to stub it with another 20+ bytes.

 strcat(argv[1], ", Agniva welcomes you");

Perhaps something like this

 if( argc < 2 )
        return -1;

    char *oBuf = calloc( strlen( argv[1] ) + 25 /* for this ", Agniva welcomes you" */ , 1);

    sprintf( oBuf, "%s%s",argv[1], ", Agniva welcomes you");
    printf("%s", oBuf);
    return 0;

Upvotes: 0

iBug
iBug

Reputation: 37237

This is my previous comment on the question, and it's almost a complete answer.

In brief, there's no extra memory space allocated for every item in argv, so when you try to strcat more string onto it, you're writing outside the buffer, which leads to undefined behavior. When you have an extra argument supplied, you're actually writing to the memory where the other argument resides. Again this is implementation-specific, and may still become undefined behavior when you run the program on another platform (like Linux).

Upvotes: 0

RbMm
RbMm

Reputation: 33744

strcat(argv[1], ", Agniva welcomes you");

this is exactly and reason — at first you can access argv[1] only in case:

if (argc > 1) // do something with argv[1]

at second, even if argv[1] point to valid memory block - you simply overwrite it with strcat - append data to it. in your concrete case argv[1] allocated from heap, and you write to memory block past it size. as result you and got A heap has been corrupted.

Upvotes: 3

Related Questions