-3

I' m trying to understad the work with a pointers. So I've wrote a test program where name is split into labels by removing the separating dots. Each label is represented as a length/data pair as follows: google.ru represents as "x\06googlex\02ru" I get signal SIGABRT when i returned from my test function I guess it's caused with my bad work with pointer.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void test(unsigned char* dns, unsigned char* host);

int main(int argc, const char * argv[])
{

    unsigned char host[]="google.ru";

    unsigned char* dnsTest=(unsigned char*)malloc(20);

    if(dnsTest==NULL)
    {
        exit(1);
    }

    test(dnsTest, host);

    printf("%s", dnsTest);

    free(dnsTest);


    return 0;
}
void test(unsigned char* dns, unsigned char* host)
{
    strcat((char*)host, ".");

    int lock=0;

    for(int i=0; i<strlen((char *)host);i++)
    {
        if(host[i]=='.')
        {

            *dns=i-lock;

            dns++;

            for(;lock<i; lock++)
            {
                *dns=host[lock];
                dns++;

            }
                lock++;
        }
    }
    *dns='\0';

}
Anton
  • 37
  • 2

1 Answers1

0

Since you tagged c++ as well, you can use new \ delete instead of malloc \ free. New will call constructor (when you will learn classes it will be useful), and new return to you exact type, so no need to cast (and casting is almost always a bad idea)

Then assertion after memory allocation with new will be redundant:

if(dnsTest==NULL)

since c++ new will throw an exception by default. If you go ahead, you can use std::string - its much more simple than c null terminated strings (but not for the task of understanding pointers).

Every other comments (about redundant strlen usage and absence of '\0' symbol) is correct too, but I want to give you two advices, how to grasp pointers.

First - read K&R - it's the Bible.

Second - if you use Microsoft Visual Studio, you can compile your code in Debug mode, and use Memory View tab. Visual Studio compiler place some magic number inside memory (link) at debug mode. They can help you with understanding where you addressing unallocated memory or how exactly your memory layout looks like.

Community
  • 1
  • 1
Andrey Suvorov
  • 511
  • 3
  • 17