0

Why this code isn't working?

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

int main(int argc,char **argv){

    char * new;
    new = malloc(10);
    const char * s1 = "hello";

    while(*s1){
        *new++ = *s1++;
    }
    printf("%s",new);

    return 0;
}

I ran the gdb and found that *s1 is not assigned to the *new. why?

1
  • 1
    You've modified new in your loop, so it no longer points to the beginning of the block you allocated -- it points to the character after the last one you copied in. You also haven't copied the null terminator. Commented Nov 28, 2017 at 5:37

2 Answers 2

5

new is pointing to one byte past the last element of whatever was copied over from s1. You should pass the pointer to the first element of new to get the entire text.

Another problem is that you are not copying over the \0 from s1 to new. You should put a \0 at the end of new before trying to print it. Otherwise you are invoking UB.

You might do something like this and check:

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

int main(int argc,char **argv){

    char * new, *new2;
    new = malloc(10);
    new2 = new;
    const char * s1 = "hello";
    while(*s1){
        printf("%c\n", *s1); // the \0 is *not* appended
        *new++ = *s1++;
    }
    *new = '\0';
    printf("%s\n",new2);
    return 0;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Also remember that new is probably not your best choice of names (though legal) because new is what allocates in C++. char *p = new; and operating on p works as well.
you are right @DavidC.Rankin will change.. also lawyer and a programmer man you are an inspiration! thank you
Nope, just bipolar (left brain/right brain thing :)
@DavidC.Rankin having bipolar makes you multi talented what ?? lol
1

Because the new is pointing to the location one after the last character copied from s1 to new.

You can do:

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

int main(int argc,char **argv){

    char *new, *tmp;
    new = malloc(10);
    if (new == NULL){
        printf ("Failed to allocate memory");
        return -1;
    }

    const char * s1 = "hello";
    tmp = new;   //take a temporary pointer and point it to new
    while(*s1){
       *tmp++ = *s1++;    //use tmp to copy data
    }
    *tmp = '\0';
    printf("%s",new);
    return 0; 
}

1 Comment

ah i want to accept both answers! thanks for ur time ppl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.