A
arnuld
I have this program which is causing confusion to me. I am told that last
printf() of main() will always print "Second", not "First". I think line:
x = myAlloc(x);
is UB. My colleague is disagreeing on this while I was saying that its UB
because there is no sequence point here. It is just like using this line:
i = i++;
But he says that sequence point will not affect the pointers and hence
this is perfectly valid ANSI C program. I am confused on this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { SIZE_LIMIT = 10 };
char* myAlloc(char* c);
int main(void)
{
char* x = malloc(SIZE_LIMIT * sizeof *x);
if(NULL == x)
{
printf("Out of Memory\n");
return EXIT_FAILURE;
}
strcpy(x, "First");
printf("x = %s\n", x);
x = myAlloc(x);
printf("x = %s\n", x);
return 0;
}
char* myAlloc(char* c)
{
c = malloc(SIZE_LIMIT * sizeof *c);
if(NULL == c)
{
printf("Out of Memory\n");
return NULL;
}
else
{
strcpy(c, "Second");
}
return c;
}
================= OUTPUT ====================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra ptrtest.c
[arnuld@dune programs]$ ./a.out
x = First
x = Second
[arnuld@dune programs]$
printf() of main() will always print "Second", not "First". I think line:
x = myAlloc(x);
is UB. My colleague is disagreeing on this while I was saying that its UB
because there is no sequence point here. It is just like using this line:
i = i++;
But he says that sequence point will not affect the pointers and hence
this is perfectly valid ANSI C program. I am confused on this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { SIZE_LIMIT = 10 };
char* myAlloc(char* c);
int main(void)
{
char* x = malloc(SIZE_LIMIT * sizeof *x);
if(NULL == x)
{
printf("Out of Memory\n");
return EXIT_FAILURE;
}
strcpy(x, "First");
printf("x = %s\n", x);
x = myAlloc(x);
printf("x = %s\n", x);
return 0;
}
char* myAlloc(char* c)
{
c = malloc(SIZE_LIMIT * sizeof *c);
if(NULL == c)
{
printf("Out of Memory\n");
return NULL;
}
else
{
strcpy(c, "Second");
}
return c;
}
================= OUTPUT ====================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra ptrtest.c
[arnuld@dune programs]$ ./a.out
x = First
x = Second
[arnuld@dune programs]$