Home > Software design >  c Increase pointer size without return new pointer
c Increase pointer size without return new pointer

Time:10-02

My teacher has me complete this(the main is hidden) and i wonder why i got an infinite loop with this solution. Task: Complete this function:

void pad_left(char *a, int n) {
}

// if length of a greater than n, do nothing
// else insert '_' util a 's length is n

Some case i got an segmentfault I try realloc but it return new ptr My solution


#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

void printChar(char *a) {
    int i = 0;
    while(a[i] != '\0') cout << a[i];
    cout << endl;
}


void insert_begin(char *a, int n) {
    for(int i = n; i > 0; i--) {
        a[i] = a[i-1];
    }
    a[n 1] = '\0';
}

void pad_left(char *a, int n) {
    int len = n - strlen(a);
    for(int i = 0; i < len; i  ) {
        insert_begin(a, strlen(a));
    }
}

Here is full code


#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

void printChar(char *a) {
    int i = 0;
    while(a[i] != '\0') cout << a[i];
    cout << endl;
}


void insert_begin(char *a, int n) {
    for(int i = n; i > 0; i--) {
        a[i] = a[i-1];
    }
    a[n 1] = '\0';
}

void pad_left(char *a, int n) {
    int len = n - strlen(a);
    for(int i = 0; i < len; i  ) {
        insert_begin(a, strlen(a));
    }
}


int main() {

    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    char a[5] = "test";
    pad_left(a, 10);

    printChar(a);
    return 0;
}

CodePudding user response:

Okay, you need some background information.

void pad_left(char *a, int n) {
}
char a[5] = "test";
pad_left(a, 10);

This is going to be a significant problem. First, you can't realloc for two reasons. First, char a[5] is a fixed array -- not an allocated array. When you pass it to pad_left, that doesn't change. realloc() does a free of the old pointer, but you can't do that, and it will cause problems. So you cannot use realloc in your solution unless you make sure the strings came from allocated memory. And you can't assume that.

So put realloc aside. You can't use that.

Next, char a[5] only allocates 5 bytes. If you start writing beyond that range (by passing in 10 to your method), you're going to step on other places. This is absolutely bad.

So... Without testing it, the rest of your code seems reasonable. You can probably get a good test if you do this:

char a[100] = "test";
pad_left(a, 10);

You'll have allocated plenty of space for padding. Try this and see if you get further.

  • Related