3

I've been working on a method which is supposed to convert a Pascal string to a C String. I was also told that the char * returned should point to a newly allocated char array containing a null-terminated C-String. The callee is responsible for calling free() on this array.

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

char *pascal_convert(void *x)
{
    int *y;
    x = y;
    char *z;
    *z = *((int*)x);
    char *arr = malloc(sizeof(*z));
    for (int i = 0; i < *y; i++)
    {
        arr[i] = z[i];
    }
    char* fin = arr;

    return fin;
}
3
  • What bugs do you have in pascal_convert? Did you test it? Commented Dec 8, 2015 at 23:01
  • 2
    why x= y instead of y = x? Commented Dec 8, 2015 at 23:04
  • I would say the "caller" is responsible for calling free(). Commented Dec 8, 2015 at 23:26

1 Answer 1

2

Many adjustments needed

char *pascal_convert(void *x)
{
    // int *y;
    // x = y;   This assignment is backwards
    unsigned char *y = x;  // Need unsigned char (unless your pascal uses wider type here)

    // y = z;
    // char *z;
    // *z = *((int*)x);
    size_t size = *y++;  // Size is just the first element

    // char *arr = malloc(sizeof(*z));
    char *arr = malloc(size + 1);  // Allocate + 1 for the null chacter

    if (arr) {  // test need as `malloc()` may fail
      // for (int i = 0; i < *y; i++) { arr[i] = z[i]; }
      memcpy(arr, y, size); 
      arr[size] = '\0';  // append null character
    } 

    // char* fin = arr;  // No need for new variable
    // return fin;
    return arr;
}
Sign up to request clarification or add additional context in comments.

2 Comments

You should also replace any NUL characters in the middle of the string with spaces or something--Pascal allows these but C does not.
@Lee Daniel Crocker Agree detection of a '\0' in a pascal string is an important consideration for robust code. Many alternatives exists on how to handle that. IMO, an embedded '\0' should result in a failure. Maybe returning NULL? Or simply also return the size and let the calling code sort it out. Side note: fgets() also gets '\0' and keeps going until '\n' - no error indication.

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.