0

I want to get Code 2 result, but if I use Code 1 there is some strange result.

I think number 116 is t's ASCII code. But I can't understand what happened in Code 1.

Can you explain what's different between Code 1 and Code 2?

Code 1

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

int main(){
        char t;
        char *p = &t;
        char *s;
        int count=0;
        char test[40] = "Test String partial copy in C\n";
        s = strchr(test,'S');
        while(!isblank(*s)){
                *(p+count) = *s;
                s++;
                printf("%d\n",count);
                count++;
        }
        *(p+count) = '\0';
        printf("%s\n",p);
}

Result: 0 116 117 118 119 120 Sy

Code 2

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

int main(){
        char *p = (char*)malloc(sizeof(char));
        char *s;
        int count=0;
        char test[40] = "Test String partial copy in C\n";
        s = strchr(test,'S');
        while(!isblank(*s)){
                *(p+count) = *s;
                s++;
                printf("%d\n",count);
                count++;
        }
        *(p+count) = '\0';
        printf("%s\n",p);
}

Result: 0 1 2 3 4 5 String

pringi
  • 3,987
  • 5
  • 35
  • 45
서동진
  • 1
  • 1
  • 1
    In the first example, where is `p` pointing? It's pointing to a ***single*** character. You write well beyond the bounds of that single character, leading to *undefined behavior*. You have the same problem in the second program, but there `p` points to a single character somewhere else in memory. – Some programmer dude Sep 27 '17 at 13:50
  • 1
    Also note that for any pointer or array `p` and index `i`, the expression `*(p + i)` is exactly equal to `p[i]`. – Some programmer dude Sep 27 '17 at 13:51
  • Both are undefined behavior. `char t; char *p = &t;` --> `char t[40]; char *p = t;` – BLUEPIXY Sep 27 '17 at 13:53
  • 1
    While [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) is really all you need to know (it makes your whole program *ill-formed* and invalid), what *actually* happening in your first program is that the compiler places local variable on the stack, and you simply overwrite your own local variables. In the second example, since the single character is allocated of the heap, it *seems* to work better. – Some programmer dude Sep 27 '17 at 13:55
  • 1
    After the first lap in the loop, `p` is pointing out in la-la-land, that's why. There's only one character allocated where it points, but you try to store a whole array there. `p` needs to point at _an array of valid, allocated memory_. Either statically or dynamically allocated. The answer to the linked duplicate will explain this. – Lundin Sep 27 '17 at 13:59

0 Answers0