varkus
varkus

Reputation: 21

Why strcat doesn't work with pointer in C?

When I execute this with a normal array it's working but with a pointer it doesn't.

#include <stdio.h>
#include <string.h>
int main()
{
    char source[]="Agdhefhe";
    char *accum = "";
    for(int i=0;i<=sizeof(*source)/sizeof(char);i++)
        {
            for(int j=0; j<i; j++)
            strcat(accum,source);
        }
        
    printf("%s",accum);
    return 0;
}

Upvotes: 0

Views: 264

Answers (2)

Clifford
Clifford

Reputation: 93556

The pointer accum points to the constant initialiser which has length 1. The result of both writing to the initialiser's data area and overrunning the allocated space is undefined.

accum must point to a writable region with sufficient space allocated to accommodate the final string.

Upvotes: 4

Bo R
Bo R

Reputation: 2371

To get it right you need to allocation enough space for the destination to write to.

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

int main(void) {
    char source[] = "Agdhefhe";
    size_t sz = 360;
    char *accum = (char *) malloc(sz + 1);
    *accum = '\0';  // needed for first strcat call
    for (int i = 0; i <= sizeof(*source) / sizeof(char); i++)
        for (int j = 0; j < i; j++)
            strncat(accum, source, sz);  // strncat used to not write too much

    printf("%s", accum);
    free(accum);
    return 0;
}

This program writes Agdhefhe but can be simplified to

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

int main(void) {
    char const source[] = "Agdhefhe";
    size_t sz = 360;
    char *accum = (char *) malloc(sz + 1);
    *accum = '\0';  // needed for first strcat call
    strncat(accum, source, sz);

    printf("%s", accum);
    free(accum);
    return 0;
}

But if you wanted to duplicate the string a number of times you write:

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

int main(void) {
    char const source[] = "Agdhefhe";
    size_t sz = 360;
    char *accum = (char *) malloc(sz + 1);
    *accum = '\0';  // needed for first strcat call
    for (int i = 0; i <= sizeof(source) / sizeof(char); i++)  // the change is here
        for (int j = 0; j < i; j++)
            strncat(accum, source, sz);

    printf("%s", accum);
    free(accum);
    return 0;
}

This writes AgdhefheAgdhefheAgdhefheAgdhefhe...Agdhefhe (360 characters).

Upvotes: 1

Related Questions