Arun Srikanth Sridhar
Arun Srikanth Sridhar

Reputation: 65

Is this an undefined behaviour?

So I just wanted to ask is this an undefined behavior when the commented line is added. Although there is no compilation errors and both of them give the same answers. I would like to know is there any difference. Is the address being overwritten by the address of a. Also If one were to do this (i.e allocate memory for b), would memcpy() be a good solution. This may be a trivial example but I would like to understand the difference.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *a;
    int *b;
    a=malloc(sizeof(int));
    //b=malloc(sizeof(int));
    int c=6;
    a=&c;
    b=a;
    printf("%d\n",*b);
    return 0;
}

Upvotes: 2

Views: 132

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134416

When you uncomment //b=malloc(sizeof(int)); part, you'll end up creating memory leak, as later, you'll be losing the pointer returned by malloc() and will have no way to free() it.

FWIW, you already have the issue with a, as you overwrite malloc()ed memory by the address of c.

It is not UB, though, a bad practice, anyway.

For the above code, you can remove both the malloc()s, safely. You don't need them.

That said, int main() should be int main(void), at least, to conform to the standards.

Upvotes: 8

MikeCAT
MikeCAT

Reputation: 75062

I don't think this code cause undefined behavior, but this code do cause memory leak.

Don't use malloc() if you don't need additional buffer.

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182893

b=malloc(sizeof(int));
int c=6;
a=&c;
b=a;

Since the value of b is changed before it's used, that you assign the return value of malloc to b makes no difference. However, you don't free it, so you do leak the memory allocated.

No UB.

Upvotes: 2

Related Questions