menu search

if i want to copy the string best school into a new space in memory what are the options of statements i can use to reserve enough space for it

thumb_up_off_alt 2 like thumb_down_off_alt 0 dislike

1 Answer

#define _GNU_SOURCE // asprintf
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    char s[] = "best school";
    // no free(); stack allocation

    char *s2 = strdup(s);

    // sizeof works here because s is an array; see later
    // strlen() which works both both array and pointers.
    char *s3 = malloc(sizeof(s));
    memcpy(s3, s, sizeof(s));

    // stack allocated (i.e. < 8k including other 
    // parameters and fails badly.
    char *s4;
    asprintf(&s4, "%s", s);
    // no free(); stack allocation 

    char *s5 = calloc(sizeof(s), 1);
    strcat(s5, s);

    char *s6 = calloc(strlen(s) + 1, 1);
    strncat(s6, s, strlen(s));

    <span style="border:0px; box-sizing:inherit; color:var(--highlight-namespace); font-family:inherit; font-stretch:inherit; font-style:inherit; font-variant:inherit; font-weight:inherit; line-height:inhe
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
eForumAfrica, where you can ask questions and receive answers from other members of the community. Find the answer to your question, help others by answering their questions.